DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(remote): 隧道崩溃与 native 持久配对,发布 v0.24.0-beta.2 (#1046)
Mao Mr7756a9afd5a3
diff --git a/.github/workflows/release-testflight.yml b/.github/workflows/release-testflight.ymlindex 54db3ce7..b09fec27 100644--- a/.github/workflows/release-testflight.yml+++ b/.github/workflows/release-testflight.yml@@ -76,7 +76,7 @@ jobs:- name: Setup verified Xcode 26.4.1uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90with:- xcode-version: '26.4.1'+ xcode-version: 26.4.1- name: Verify selected toolchainrun: |diff --git a/app.json b/app.jsonindex b917b9b3..faa84560 100644--- a/app.json+++ b/app.json@@ -2,14 +2,14 @@"expo": {"name": "DSH Mobile","slug": "dsh-bridge",- "version": "0.24.0-beta.1",+ "version": "0.24.0-beta.2","scheme": "dshbridge","orientation": "portrait","userInterfaceStyle": "automatic","icon": "./assets/native/icon.png","android": {"package": "com.dshtauri.dshbridge",- "versionCode": 21008,+ "versionCode": 21009,"adaptiveIcon": {"foregroundImage": "./assets/native/adaptive-icon.png","backgroundColor": "#ffffff"diff --git a/package.json b/package.jsonindex 0431725c..8d2f93a3 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "deepseek-harness-desktop","type": "module",- "version": "0.24.0-beta.1",+ "version": "0.24.0-beta.2","private": true,"packageManager": "[email protected]","description": "Desktop application for DeepSeek Harness (dsh) — one-click local install and launch, no Node.js setup required.",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 b5446f3c..09605b67 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@@ -357,14 +357,30 @@ describe('接入面板', () => {await waitFor(() => expect(getCalls(BASE, 'GET').length).toBeGreaterThanOrEqual(2))})- it('永久码未签发时只给生成按钮,生成后当次明文可见并走 POST /access/token', async () => {+ it('只用临时码配对也能撤销所有设备授权,不必先生成永久码', async () => {+ once(+ replies.ok(statusPayload({ auth: authPayload({ hasToken: false }), pairing: pairingPayload() })),+ replies.ok(statusPayload({ auth: authPayload({ hasToken: false }), pairing: pairingPayload({ code: 'WX67YZ89' }) })),+ )+ render(<AccessSection t={t} />)+ await screen.findByTestId('access-pairing-code')+ const revoke = screen.getByTestId('access-token-revoke')+ expect(revoke.textContent).toBe(en['access.token.revoke'])+ expect((revoke as HTMLButtonElement).disabled).toBe(false)+ expect(screen.queryByTestId('access-permanent-value')).toBeNull()+ fireEvent.click(revoke)+ await waitFor(() => expect(getCalls(TOKEN, 'DELETE')).toHaveLength(1))+ await waitFor(() => expect(screen.getByTestId('access-pairing-code').textContent).toBe('WX67YZ89'))+ })++ it('永久码未签发时给生成按钮,生成后当次明文可见并走 POST /access/token', async () => {once(replies.ok(statusPayload()), replies.ok(statusPayload({ auth: authPayload({ token: PERMANENT }) })))render(<AccessSection t={t} />)await screen.findByTestId('access-token-rotate')expect(screen.getByTestId('access-token-rotate').textContent).toBe(en['access.token.generate'])expect(screen.queryByTestId('access-permanent-value')).toBeNull()expect(screen.queryByTestId('access-permanent-reveal')).toBeNull()- expect(screen.queryByTestId('access-token-revoke')).toBeNull()+ expect(screen.getByTestId('access-token-revoke').textContent).toBe(en['access.token.revoke'])fireEvent.click(screen.getByTestId('access-token-rotate'))await waitFor(() => expect(getCalls(TOKEN, 'POST')).toHaveLength(1))await screen.findByTestId('access-permanent-value')@@ -384,7 +400,7 @@ describe('接入面板', () => {const reveal = screen.getByTestId('access-permanent-reveal')expect(reveal.textContent).toBe(en['access.token.reveal'])expect(reveal.getAttribute('aria-pressed')).toBe('false')- expect(Array.from(screen.getByTestId('access-permanent').children, child => child.getAttribute('data-testid'))).toEqual(['access-token-revoke', 'access-permanent-reveal', 'access-permanent-value'])+ expect(Array.from(screen.getByTestId('access-permanent').children, child => child.getAttribute('data-testid'))).toEqual(['access-permanent-reveal', 'access-permanent-value'])expect(screen.getByTestId('access-permanent-value').className).toContain('border-l-[0.5px]')fireEvent.click(reveal)await waitFor(() => expect(screen.getByTestId('access-permanent-value').textContent).toBe(PERMANENT))diff --git a/packages/dsh-tauri-remote/src/client/components/access-section.tsx b/packages/dsh-tauri-remote/src/client/components/access-section.tsxindex 3d919b2b..f0e669b6 100644--- a/packages/dsh-tauri-remote/src/client/components/access-section.tsx+++ b/packages/dsh-tauri-remote/src/client/components/access-section.tsx@@ -317,7 +317,9 @@ export function AccessSection({ t }: AccessSectionProps): ReactElement {</Card><Card>- <Row title={t('access.control.title')} hint={t('access.control.hint')}>{null}</Row>+ <Row title={t('access.control.title')} hint={t('access.control.hint')}>+ <Button variant="ghost" size="sm" data-testid="access-token-revoke" disabled={busy} onClick={revokeToken}>{t('access.token.revoke')}</Button>+ </Row><Row title={t('access.pairing.title')} hint={t('access.pairing.hint')}><div className="flex flex-none items-center gap-[8px]" data-testid="access-pairing">{pairing === undefined@@ -338,7 +340,6 @@ export function AccessSection({ t }: AccessSectionProps): ReactElement {? <Button variant="outline" size="sm" data-testid="access-token-rotate" disabled={busy} onClick={issueToken}>{t('access.token.generate')}</Button>: (<>- <Button variant="ghost" size="sm" data-testid="access-token-revoke" disabled={busy} onClick={revokeToken}>{t('access.token.revoke')}</Button><Button variant="outline" size="sm" data-testid="access-permanent-reveal" aria-pressed={revealed} aria-label={t(revealed ? 'access.token.hide' : 'access.token.reveal')} onClick={() => setRevealed(value => !value)}>{t(revealed ? 'access.token.hide' : 'access.token.reveal')}</Button><code className="border-l-[0.5px] border-border-l2 pl-[8px] text-[14px] leading-[20px] tracking-[2px]" data-testid="access-permanent-value">{revealed ? token : '••••••••'}</code></>diff --git a/packages/dsh-tauri-remote/src/client/locales/index.ts b/packages/dsh-tauri-remote/src/client/locales/index.tsindex ddd3c24b..12863c80 100644--- a/packages/dsh-tauri-remote/src/client/locales/index.ts+++ b/packages/dsh-tauri-remote/src/client/locales/index.ts@@ -149,7 +149,7 @@ export const zh = {'access.tunnel.state.running': '隧道运行中','access.tunnel.state.error': '隧道异常','access.control.title': '访问控制',- 'access.control.hint': '打开局域网或隧道后,这里给出配对用的凭据。',+ 'access.control.hint': '配对后设备长期记住授权。撤销会清除全部设备授权、会话和访问码,所有设备需要重新配对。','access.lan.title': '局域网','access.lan.hint': '打开后同一网络的设备可访问本机 dsh;关闭时不监听。','access.lan.addressHint': '推荐地址按可达性排序,「全部网卡」用于地址会变或多网卡的场景。',@@ -172,7 +172,7 @@ export const zh = {'access.token.title': '永久访问码','access.token.hint': '长期不变;泄露后可重新生成,旧码立即失效。','access.token.generate': '生成',- 'access.token.revoke': '作废',+ 'access.token.revoke': '撤销配对授权','access.token.reveal': '显示','access.token.hide': '隐藏',} as const@@ -327,7 +327,7 @@ export const en: Record<keyof typeof zh, string> = {'access.tunnel.state.running': 'Tunnel running','access.tunnel.state.error': 'Tunnel failed','access.control.title': 'Access control',- 'access.control.hint': 'Pairing credentials appear here once the local network or tunnel is on.',+ 'access.control.hint': 'Paired devices remember authorization. Revoking clears all device authorizations, sessions and access codes; every device must pair again.','access.lan.title': 'Local network','access.lan.hint': 'Turn this on to let devices on the same network reach this machine; off stops the listener.','access.lan.addressHint': 'Recommended addresses are sorted by reachability; "all interfaces" suits multi-NIC hosts or addresses that change.',@@ -350,7 +350,7 @@ export const en: Record<keyof typeof zh, string> = {'access.token.title': 'Permanent access code','access.token.hint': 'Does not rotate; regenerate it to invalidate the old code.','access.token.generate': 'Generate',- 'access.token.revoke': 'Revoke',+ 'access.token.revoke': 'Revoke paired access','access.token.reveal': 'Show','access.token.hide': 'Hide',}diff --git a/packages/dsh-tauri-remote/src/host/service/access.test.ts b/packages/dsh-tauri-remote/src/host/service/access.test.tsindex eb29762e..61b61914 100644--- a/packages/dsh-tauri-remote/src/host/service/access.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.test.ts@@ -11,6 +11,7 @@ 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 { signDeviceSession, signSession, verifyDeviceSession, verifySession } from '../utils/auth'import { access } from './access'import { defaultAccessDocument, enumerateAddresses, isReachableAddress, readAccessDocument, writeAccessDocument } from './access.utils'import { gateway } from './gateway'@@ -242,13 +243,57 @@ async function enable(address = '127.0.0.1', port?: number): Promise<RemoteAcces}describe('access 监听生命周期', () => {+ it('会话密钥落盘且模块重载保持授权,撤销使设备票据与会话失效', async () => {+ await access.ensureAuth()+ const secret = access.policy().sessionSecret+ expect(secret).toMatch(/^[\w-]{43}$/u)+ expect(storedDocument().auth.sessionSecret).toBe(secret)+ const now = Date.now()+ const cookie = signSession(secret, now).value+ const device = signDeviceSession(secret, now).value+ const document = readFileSync(documentFile(), 'utf8')+ vi.resetModules()+ const fresh = (await import('./access')).access+ try {+ expect(fresh.policy().sessionSecret).toBe(secret)+ await fresh.restore()+ expect(readFileSync(documentFile(), 'utf8')).toBe(document)+ expect(verifySession(cookie, fresh.policy().sessionSecret, now)).toBe(true)+ expect(verifyDeviceSession(device, fresh.policy().sessionSecret, now + 365 * 24 * 60 * 60 * 1000)).toBe(true)+ const code = fresh.policy().pairingCode+ await fresh.revoke()+ expect(fresh.policy().sessionSecret).not.toBe(secret)+ expect(fresh.policy().pairingCode).not.toBe(code)+ expect(verifySession(cookie, fresh.policy().sessionSecret, now)).toBe(false)+ expect(verifyDeviceSession(device, fresh.policy().sessionSecret, now)).toBe(false)+ expect(JSON.stringify(await fresh.status())).not.toContain(fresh.policy().sessionSecret)+ }+ finally {+ await fresh.dispose()+ }+ })++ it('恢复旧配置只补一次会话密钥,即使只开隧道也保存授权', async () => {+ const document = { ...defaultAccessDocument(), auth: { enabled: true, token: null, scope: 'all' as const } }+ writeAccessDocument(document)+ await access.restore()+ const first = storedDocument()+ expect(first.auth.sessionSecret).toMatch(/^[\w-]{43}$/u)+ expect(first).toEqual({ ...document, auth: { ...document.auth, sessionSecret: first.auth.sessionSecret } })+ const saved = readFileSync(documentFile(), 'utf8')+ await access.restore()+ access.policy()+ expect(readFileSync(documentFile(), 'utf8')).toBe(saved)+ expect(JSON.stringify(await access.status())).not.toContain(first.auth.sessionSecret ?? 'missing-secret')+ })+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' })+ expect(storedDocument().auth).toEqual({ enabled: true, token: null, scope: 'public_only', sessionSecret: access.policy().sessionSecret })})it('隧道前置认证仅使用配对码,重复调用不生成永久凭据', async () => {@@ -256,7 +301,7 @@ describe('access 监听生命周期', () => {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' })+ expect(storedDocument().auth).toEqual({ enabled: true, token: null, scope: 'public_only', sessionSecret: access.policy().sessionSecret })const code = access.policy().pairingCodeawait access.ensureAuth()expect(access.policy().pairingCode).toBe(code)@@ -384,7 +429,7 @@ describe('access 监听生命周期', () => {expect(restored.port).toBe(applied.port)expect(restored.link).toBe(applied.link)const stored = storedDocument()- expect(stored).toEqual({ ...defaultAccessDocument(), enabled: true, listen: { address: '127.0.0.1', port }, auth: { enabled: true, token: null, scope: 'public_only' } })+ expect(stored).toEqual({ ...defaultAccessDocument(), enabled: true, listen: { address: '127.0.0.1', port }, auth: { enabled: true, token: null, scope: 'public_only', sessionSecret: access.policy().sessionSecret } })})it('恢复失败时保持关闭并给出可读原因,且不静默改写配置', async () => {@@ -583,7 +628,7 @@ describe('access 认证与来源判定(经真实网关)', () => {expect(again.headers.location).toBe('/')})- it('作废 Token 后旧链接失效,已签发的会话不受影响', async () => {+ it('撤销授权后旧链接和已签发会话立即失效', async () => {const status = await enable()await access.apply({ authEnabled: true, scope: 'public_only' })const rotated = await access.rotate()@@ -594,7 +639,7 @@ describe('access 认证与来源判定(经真实网关)', () => {expect(revoked.auth.hasToken).toBe(false)expect(revoked.link).toBe(`http://127.0.0.1:${status.port}/`)expect((await call(status.port, `/?auth=${token}`, { source: 'public' })).status).toBe(401)- expect((await call(status.port, '/api/probe', { source: 'public', cookie })).status).toBe(200)+ expect((await call(status.port, '/api/probe', { source: 'public', cookie })).status).toBe(401)})it('配对码连续错误达阈值后封禁并返回可读剩余时间', async () => {diff --git a/packages/dsh-tauri-remote/src/host/service/access.ts b/packages/dsh-tauri-remote/src/host/service/access.tsindex 15d00649..56873e73 100644--- a/packages/dsh-tauri-remote/src/host/service/access.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.ts@@ -19,8 +19,6 @@ const NO_LOCAL_PORT = '无法确定本机 DSH 端口(宿主 webserver 未暴const CORRUPT_DOCUMENT = 'access.json 解析失败:已按未配置处理,写操作被拒绝以免覆盖原文件(请先修复或移走该文件)'-const SESSION_SECRET = createSessionSecret()-let failure: string | undefinedlet sequence = 0@@ -30,7 +28,7 @@ let events: RemoteAccessEvent[] = []export const access = defineService({/** 网关每次判定都重新取用:配置与凭据变更立即生效(S2 §7.4)。 */policy(): RemoteAuthPolicy {- return { ...policyOf(readAccessDocument().document, SESSION_SECRET), pairingCode: pairingCodeOf().code, consumePairingCode }+ return { ...policyOf(readAccessDocument().document), pairingCode: pairingCodeOf().code, consumePairingCode }},async status(): Promise<RemoteAccessStatus> {@@ -96,6 +94,8 @@ export const access = defineService({const next = patchAccessDocument(parsed.document, body, enumerateAddresses())if (body.enabled === true && body.authEnabled === undefined)next.auth.enabled = true+ if (next.auth.enabled)+ next.auth.sessionSecret ??= createSessionSecret()writeAccessDocument(next)await activate(next)return await access.status()@@ -105,7 +105,7 @@ export const access = defineService({const parsed = readAccessDocument()if (parsed.corrupt)throw new Error(CORRUPT_DOCUMENT)- const next = { ...parsed.document, auth: { ...parsed.document.auth, enabled: true } }+ const next = { ...parsed.document, auth: { ...parsed.document.auth, enabled: true, sessionSecret: parsed.document.auth.sessionSecret ?? createSessionSecret() } }writeAccessDocument(next)await activate(next)return await access.status()@@ -124,8 +124,10 @@ export const access = defineService({const parsed = readAccessDocument()if (parsed.corrupt)throw new Error(CORRUPT_DOCUMENT)- writeAccessDocument({ ...parsed.document, auth: { ...parsed.document.auth, token: null } })- note('token', '链接 Token 已作废,已签发的会话不受影响')+ writeAccessDocument({ ...parsed.document, auth: { ...parsed.document.auth, token: null, sessionSecret: createSessionSecret() } })+ gateway.revoke()+ resetPairingCode()+ note('token', '链接 Token、已配对设备与会话授权已撤销')return await access.status()},@@ -138,6 +140,10 @@ export const access = defineService({}for (const warning of parsed.warnings)note('state', warning)+ if (parsed.document.auth.enabled && parsed.document.auth.sessionSecret === undefined) {+ parsed.document.auth.sessionSecret = createSessionSecret()+ writeAccessDocument(parsed.document)+ }if (!parsed.document.enabled) {failure = undefinedreturndiff --git a/packages/dsh-tauri-remote/src/host/service/access.types.ts b/packages/dsh-tauri-remote/src/host/service/access.types.tsindex d60eeb8f..00065424 100644--- a/packages/dsh-tauri-remote/src/host/service/access.types.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.types.ts@@ -9,6 +9,7 @@ export interface RemoteAccessAuthDocument {enabled: booleantoken: string | nullscope: RemoteAuthScope+ sessionSecret?: string}export interface RemoteAccessDocument {diff --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 778f2a6d..4dcef674 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,6 +4,7 @@ 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 { createSessionSecret } 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[] = []@@ -98,6 +99,20 @@ describe('parseAccessDocument', () => {expect(serializeAccessDocument(parsed.document)).not.toContain('password')})+ it('保留随机会话密钥并拒绝无效密钥,补丁不会清除授权密钥', () => {+ const secret = createSessionSecret()+ const parsed = parseAccessDocument(JSON.stringify({ auth: { enabled: true, sessionSecret: secret } }))+ expect(parsed.document.auth.sessionSecret).toBe(secret)+ expect(parsed.warnings).toEqual([])+ expect(parseAccessDocument(serializeAccessDocument(parsed.document)).document.auth.sessionSecret).toBe(secret)+ expect(patchAccessDocument(parsed.document, { scope: 'all' }, []).auth.sessionSecret).toBe(secret)+ for (const sessionSecret of ['', 'weak-secret', null, 123, `${secret}x`]) {+ const invalid = parseAccessDocument(JSON.stringify({ auth: { sessionSecret } }))+ expect(invalid.document.auth.sessionSecret).toBeUndefined()+ expect(invalid.warnings).toEqual(['access.json 的 auth.sessionSecret 非法,已丢弃'])+ }+ })+it('文件缺失或全为空白时回落默认文档且不算损坏', () => {const missing = parseAccessDocument(undefined)expect(missing.document).toEqual(defaultAccessDocument())@@ -400,6 +415,8 @@ describe('pairingLinksOf', () => {describe('policyOf', () => {it('把文档映射为网关认证快照', () => {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' })+ expect(policyOf(document)).toEqual({ enabled: true, scope: 'all', linkToken: 'tok', sessionSecret: '' })+ const sessionSecret = createSessionSecret()+ expect(policyOf({ ...document, auth: { ...document.auth, sessionSecret } }).sessionSecret).toBe(sessionSecret)})})diff --git a/packages/dsh-tauri-remote/src/host/service/access.utils.ts b/packages/dsh-tauri-remote/src/host/service/access.utils.tsindex 73bd89c8..0d557115 100644--- a/packages/dsh-tauri-remote/src/host/service/access.utils.ts+++ b/packages/dsh-tauri-remote/src/host/service/access.utils.ts@@ -18,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', 'token', 'scope'])+const AUTH_KEYS = new Set(['enabled', 'token', 'scope', 'sessionSecret'])const TUNNEL_KEYS = new Set(['enabled', 'mode', 'token', 'hostname'])@@ -136,12 +136,12 @@ export function isSelectableAddress(address: string, addresses: RemoteAccessAddrreturn addresses.some(entry => entry.address === address)}-export function policyOf(document: RemoteAccessDocument, sessionSecret: string): RemoteAuthPolicy {+export function policyOf(document: RemoteAccessDocument): RemoteAuthPolicy {return {enabled: document.auth.enabled,scope: document.auth.scope,linkToken: document.auth.token,- sessionSecret,+ sessionSecret: document.auth.sessionSecret ?? '',}}@@ -326,6 +326,10 @@ function readAuth(value: unknown, document: RemoteAccessDocument, warnings: stridocument.auth.token = value.tokenelse if (value.token !== undefined && value.token !== null)warnings.push('access.json 的 auth.token 非法,已丢弃')+ if (typeof value.sessionSecret === 'string' && /^[\w-]{43}$/u.test(value.sessionSecret))+ document.auth.sessionSecret = value.sessionSecret+ else if (value.sessionSecret !== undefined)+ warnings.push('access.json 的 auth.sessionSecret 非法,已丢弃')}function readTunnel(value: unknown, document: RemoteAccessDocument, warnings: string[]): void {diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.test.tsindex d10d1d66..47459206 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.test.ts@@ -1,5 +1,5 @@import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'-import type { AddressInfo } from 'node:net'+import type { AddressInfo, Socket } from 'node:net'import type { Duplex } from 'node:stream'import type { RemoteAuthPolicy, RemoteGatewayEntryKind, RemoteGatewayEvent, RemoteGatewayStartOptions } from '../types/index'import { Buffer } from 'node:buffer'@@ -1607,6 +1607,173 @@ describe('gateway 认证要素', () => {})})+describe('gateway native 长期授权', () => {+ const issuedAt = 1_700_000_000_000+ const deviceToken = 'v1.1700000000000.0.d00a01b8c953df972df9b96b0d093564f73bf36fbf0f4119e5bd5c02e62b8f77'+ const sessionPath = '/api/tauri/remote/access/session'++ it('临时配对成功后用已认证会话取得长期授权,不缓存或转发凭据', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(issuedAt)+ const first = pairingCodeOf()+ const policy = policyOf({ linkToken: null, pairingCode: first.code, consumePairingCode })+ const status = await startEntry('tunnel', upstream, { auth: () => policy })+ const login = await call(status.port, `/?auth=${first.code}`, { headers: tunnelHeaders('') })+ expect(login.status).toBe(302)+ expect(pairingCodeOf().usedSeq).toBe(1)+ const cookie = (login.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''+ const reply = await call(status.port, sessionPath, { headers: tunnelHeaders(cookie) })+ expect(reply.status).toBe(200)+ expect(JSON.parse(reply.body.toString())).toEqual({ token: deviceToken })+ expect(reply.headers['cache-control']).toBe('no-store')+ expect(reply.headers['set-cookie']).toBeUndefined()+ expect(upstream.calls).toHaveLength(0)+ })++ it.each(['private', 'loopback', 'public'] as const)('%s 来源免密或未登录时不能取得长期授权', async (source) => {+ const status = await startEntry('inbound', upstream, { auth: () => policyOf(), tokenProvider: upstream.mintUrlFor })+ const reply = await call(status.port, sessionPath, { headers: markerHeaders(source) })+ expect(reply.status).toBe(401)+ expect(JSON.parse(reply.body.toString())).toEqual({ error: '需要认证后才能访问。' })+ expect(reply.headers['set-cookie']).toBeUndefined()+ expect(upstream.calls).toHaveLength(0)+ })++ it('认证停用时已有会话也不能取得长期授权', async () => {+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ enabled: false }), tokenProvider: upstream.mintUrlFor })+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ const reply = await call(status.port, sessionPath, { headers: markerHeaders('private', { cookie }) })+ expect(reply.status).toBe(401)+ expect(upstream.calls).toHaveLength(0)+ })++ it('跨站来源不能取得长期授权或清除会话', async () => {+ const status = await startEntry('inbound', upstream, { auth: () => policyOf() })+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ for (const method of ['GET', 'DELETE']) {+ const reply = await call(status.port, sessionPath, { method, headers: markerHeaders('public', { cookie, origin: 'https://evil.example' }) })+ expect(reply.status).toBe(403)+ expect(reply.headers['set-cookie']).toBeUndefined()+ }+ expect(upstream.calls).toHaveLength(0)+ })++ it.each(['POST', 'HEAD', 'OPTIONS'])('%s 不能取得长期授权或透传会话端点', async (method) => {+ const status = await startEntry('inbound', upstream, { auth: () => policyOf() })+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ const reply = await call(status.port, sessionPath, { method, headers: markerHeaders('public', { cookie }) })+ expect(reply.status).toBe(405)+ expect(reply.headers.allow).toBe('GET, DELETE')+ expect(reply.headers['set-cookie']).toBeUndefined()+ expect(upstream.calls).toHaveLength(0)+ })++ it('设备授权一年后仍可重新取得有限会话,且不消费新的临时配对码', async () => {+ const now = issuedAt + 365 * 24 * 60 * 60 * 1000+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now)+ const code = pairingCodeOf().code+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf({ linkToken: null, pairingCode: code, consumePairingCode }), tokenProvider: upstream.mintUrlFor })+ const reply = await call(status.port, `/?auth=${deviceToken}`, { headers: tunnelHeaders('') })+ expect(reply.status).toBe(302)+ expect(reply.headers.location).toBe('/')+ const setCookie = (reply.headers['set-cookie'] ?? [])[0] ?? ''+ expect(setCookie).toContain('; Max-Age=2592000; Path=/; HttpOnly; SameSite=Lax')+ const cookie = setCookie.split(';')[0] ?? ''+ expect((await call(status.port, '/api/ping', { headers: tunnelHeaders(cookie) })).status).toBe(200)+ expect(pairingCodeOf().usedSeq).toBe(0)+ clock.mockReturnValue(now + 30 * 24 * 60 * 60 * 1000)+ expect((await call(status.port, '/api/ping', { headers: tunnelHeaders(cookie) })).status).toBe(401)+ expect((await call(status.port, `/?auth=${deviceToken}`, { headers: tunnelHeaders('') })).status).toBe(302)+ expect(upstream.calls.every(request => !request.url.includes(deviceToken))).toBe(true)+ })++ it('设备授权链接在已有有效会话时也跳到干净 URL,不透传长期凭据', async () => {+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf(), tokenProvider: upstream.mintUrlFor })+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ const reply = await call(status.port, `/?auth=${deviceToken}`, { headers: tunnelHeaders(cookie) })+ expect(reply.status).toBe(302)+ expect(reply.headers.location).toBe('/')+ expect(upstream.calls).toHaveLength(0)+ })++ it('设备授权不是普通会话 cookie,普通会话也不能充当设备授权', async () => {+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf() })+ const reply = await call(status.port, sessionPath, { headers: tunnelHeaders(`dsh_remote_session=${deviceToken}`) })+ expect(reply.status).toBe(401)+ const session = signSession('session-secret', Date.now()).value+ expect((await call(status.port, `/?auth=${session}`, { headers: tunnelHeaders('') })).status).toBe(401)+ expect(upstream.calls).toHaveLength(0)+ })++ it('授权密钥轮换后旧设备授权和已签会话均被拒绝', async () => {+ let policy = policyOf()+ const status = await startEntry('tunnel', upstream, { auth: () => policy })+ const login = await call(status.port, `/?auth=${deviceToken}`, { headers: tunnelHeaders('') })+ expect(login.status).toBe(302)+ const cookie = (login.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''+ policy = { ...policy, sessionSecret: 'revoked-session-secret' }+ expect((await call(status.port, `/?auth=${deviceToken}`, { headers: tunnelHeaders('') })).status).toBe(401)+ expect((await call(status.port, sessionPath, { headers: tunnelHeaders(cookie) })).status).toBe(401)+ expect((await call(status.port, '/api/ping', { headers: tunnelHeaders(cookie) })).status).toBe(401)+ expect(upstream.calls).toHaveLength(0)+ })++ it('冷缓存铸造期间撤销授权后不再把已接纳的写请求发往上游', async () => {+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ let release = (): void => {}+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ const provider = vi.fn(async (authority: string) => {+ await gate+ return await upstream.mintUrlFor(authority)+ })+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf(), tokenProvider: provider })+ const pending = call(status.port, '/api/echo', { method: 'POST', headers: tunnelHeaders(cookie), body: 'must-not-forward' }).catch((error: unknown) => error)+ try {+ await vi.waitFor(() => expect(provider).toHaveBeenCalledOnce())+ gateway.revoke()+ expect(await pending).toMatchObject({ code: 'ECONNRESET' })+ }+ finally {+ release()+ }+ const resumed = await call(status.port, '/api/ping', { headers: tunnelHeaders(cookie) })+ expect(resumed.status).toBe(200)+ expect(upstream.calls.map(request => request.url)).toEqual(['/?token=launch-token-1', '/api/ping'])+ })++ it.each(['inbound', 'tunnel'] as const)('删除后在 %s 入口重新配对时忽略残留会话,仍需新的配对码', async (kind) => {+ const status = await startEntry(kind, upstream, { auth: () => policyOf(), tokenProvider: upstream.mintUrlFor })+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ const headers = kind === 'tunnel' ? tunnelHeaders(cookie) : markerHeaders('private', { cookie })+ const challenge = await call(status.port, '/?pair=1', { headers: { ...headers, ...navigation() } })+ expect(challenge.status).toBe(401)+ expect(challenge.body.toString()).toContain('<form id="loginForm" method="post">')+ expect(challenge.headers['set-cookie']).toEqual(['dsh_remote_session=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax'])+ expect(upstream.calls).toHaveLength(0)+ const login = await call(status.port, '/?pair=1', {+ method: 'POST',+ headers: { ...headers, ...navigation(), 'content-type': 'application/x-www-form-urlencoded' },+ body: 'code=AB23CD45',+ })+ expect(login.status).toBe(302)+ expect(login.headers.location).toBe('/')+ const pairedCookie = (login.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''+ expect(pairedCookie).toContain('dsh_remote_session=')+ expect((await call(status.port, sessionPath, { headers: { ...headers, cookie: pairedCookie } })).status).toBe(200)+ })++ it('退出配对会话只清除当前 cookie,不在上游残留连接或凭据', async () => {+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf() })+ const reply = await call(status.port, sessionPath, { method: 'DELETE', headers: tunnelHeaders('') })+ expect(reply.status).toBe(204)+ expect(reply.headers['set-cookie']).toEqual(['dsh_remote_session=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax'])+ expect(reply.headers['cache-control']).toBe('no-store')+ expect(reply.body.length).toBe(0)+ expect(upstream.calls).toHaveLength(0)+ })+})+describe('gateway 内部来源标识', () => {it('把分类与会话标识注入到本机上游,隧道入口恒定声明 tunnel', async () => {const inbound = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })@@ -2068,11 +2235,37 @@ describe('gateway Upgrade 例外', () => {expect(gateway.status('entry')).toMatchObject({ state: 'stopped', connections: 0 })})- it('升级连接被客户端强行中断后网关仍然可用', async () => {+ it('撤销授权关闭入站与隧道的在途升级连接,保留监听端口和出站连接', async () => {+ const cookie = `dsh_remote_session=${signSession('session-secret', Date.now()).value}`+ const inbound = await gateway.start({ id: 'inbound', kind: 'inbound', upstream: upstream.origin, port: 0, auth: () => policyOf(), tokenProvider: upstream.mintUrlFor })+ const tunnel = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, auth: () => policyOf(), tokenProvider: upstream.mintUrlFor })+ const outbound = await gateway.start({ id: 'outbound', kind: 'outbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor })+ const incoming = await upgraded(inbound.port, '/api/remote.mux', markerHeaders('public', { cookie }))+ const tunneled = await upgraded(tunnel.port, '/api/remote.mux', tunnelHeaders(cookie))+ const outgoing = await upgraded(outbound.port, '/api/remote.mux', {})+ const closed = [incoming, tunneled].map((reply) => {+ const pending = once(reply.socket, 'close')+ reply.socket.resume()+ return pending+ })+ gateway.revoke()+ await Promise.all(closed)+ await vi.waitFor(() => {+ expect(gateway.status('inbound')).toMatchObject({ state: 'listening', port: inbound.port, connections: 0 })+ expect(gateway.status('tunnel')).toMatchObject({ state: 'listening', port: tunnel.port, connections: 0 })+ })+ expect(gateway.status('outbound')).toMatchObject({ state: 'listening', port: outbound.port, connections: 1 })+ expect(outgoing.socket.destroyed).toBe(false)+ expect((await call(inbound.port, '/api/ping', { headers: markerHeaders('public', { cookie }) })).status).toBe(200)+ outgoing.socket.destroy()+ })++ it('升级连接被客户端 TCP 重置后不抛未捕获异常,网关仍然可用', async () => {const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })const reply = await upgraded(status.port, '/api/remote.mux', markerHeaders('private'))expect(reply.status).toBe(101)- reply.socket.destroy()+ const socket = reply.socket as Socket+ socket.resetAndDestroy()await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))const after = await call(status.port, '/api/ping', { headers: markerHeaders('private') })expect(after.status).toBe(200)@@ -2450,7 +2643,9 @@ function freePortAt(port: number): Promise<{ port: number, release: () => Promis/** 占用 P 且保证 P+1 空闲,使「回落到下一个可用端口」有唯一确定的期望值。 */async function occupiedPortWithFreeNext(): Promise<{ port: number, release: () => Promise<void> }> {for (let attempt = 0; attempt < 5; attempt++) {- const base = await freePort()+ const base = await freePortAt(25_000 + attempt * 32)+ if (base === undefined)+ continueconst next = await freePortAt(base.port + 1)if (next !== undefined) {await next.release()diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.ts b/packages/dsh-tauri-remote/src/host/service/gateway.tsindex 75ce2046..41ee33fb 100644--- a/packages/dsh-tauri-remote/src/host/service/gateway.ts+++ b/packages/dsh-tauri-remote/src/host/service/gateway.ts@@ -7,7 +7,7 @@ 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, verifySession } from '../utils/auth'+import { rateLimitAfterFailure, rateLimitBlockedMs, signDeviceSession, signSession, tokenMatches, verifyDeviceSession, 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'@@ -90,6 +90,19 @@ export const gateway = defineService({await stopEntry(id)},+ revoke(): void {+ for (const entry of entries.values()) {+ if (entry.kind === 'outbound')+ continue+ for (const socket of entry.sockets)+ socket.destroy()+ for (const request of entry.requests)+ request.destroy()+ for (const socket of entry.upstreamSockets)+ socket.destroy()+ }+ },+status(id: string): RemoteGatewayEntryStatus | undefined {const entry = entries.get(id)return entry === undefined ? undefined : entryStatus(entry)@@ -247,6 +260,7 @@ function listenAt(entry: GatewayEntry, port: number): Promise<Server> {server.on('connection', (socket) => {entry.sockets.add(socket)entry.connections += 1+ socket.on('error', () => socket.destroy())socket.on('close', () => {entry.sockets.delete(socket)entry.connections = Math.max(0, entry.connections - 1)@@ -287,12 +301,39 @@ async function dispatchRequest(entry: GatewayEntry, request: IncomingMessage, rereturn}const policy = entry.auth?.()+ if (entry.kind !== 'outbound' && url.pathname === '/api/tauri/remote/access/session') {+ if (request.method === 'DELETE') {+ response.writeHead(204, { 'set-cookie': `${SESSION_COOKIE}=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax`, 'cache-control': 'no-store' })+ response.end()+ return+ }+ if (request.method !== 'GET') {+ response.setHeader('allow', 'GET, DELETE')+ writeJson(response, 405, '该端点仅支持 GET 与 DELETE。', 0)+ return+ }+ const now = Date.now()+ if (!isAuthConfigured(policy) || !verifySession(parseCookieHeader(cookieHeaderOf(request.headers.cookie)).get(SESSION_COOKIE), policy.sessionSecret, now)) {+ writeAuthChallenge(request, response, undefined, 401, 0)+ return+ }+ const body = JSON.stringify({ token: signDeviceSession(policy.sessionSecret, now).value })+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-length': String(Buffer.byteLength(body)), 'cache-control': 'no-store' })+ response.end(body)+ return+ }const decision = decideSourceAccess(source, policy)if (decision === 'deny') {writeDenied(request, response, DENIED_REASON)return}- const exchange = entry.kind !== 'outbound' && source !== 'loopback' && isAuthConfigured(policy) && url.pathname === '/' && ((request.method === 'GET' && url.searchParams.has(AUTH_QUERY)) || isLoginSubmission(request))+ const pairing = url.pathname === '/' && url.searchParams.get('pair') === '1'+ if (entry.kind !== 'outbound' && isAuthConfigured(policy) && pairing && request.method === 'GET' && !url.searchParams.has(AUTH_QUERY)) {+ response.setHeader('set-cookie', `${SESSION_COOKIE}=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax`)+ writeAuthChallenge(request, response, undefined, 401, 0)+ return+ }+ const exchange = entry.kind !== 'outbound' && isAuthConfigured(policy) && (source !== 'loopback' || url.searchParams.get(AUTH_QUERY)?.startsWith('v1.') || pairing) && 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))return@@ -308,16 +349,23 @@ function sourceOf(entry: GatewayEntry, request: IncomingMessage, session: stringasync 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)- if (verifySession(parseCookieHeader(cookieHeaderOf(request.headers.cookie)).get(SESSION_COOKIE), policy.sessionSecret, now))+ const url = new URL(request.url ?? '/', 'http://gateway.invalid')+ const provided = request.method === 'GET' && url.pathname === '/' ? url.searchParams.get(AUTH_QUERY) ?? undefined : undefined+ const pairing = url.pathname === '/' && url.searchParams.get('pair') === '1'+ const authenticated = !pairing && verifySession(parseCookieHeader(cookieHeaderOf(request.headers.cookie)).get(SESSION_COOKIE), policy.sessionSecret, now)+ if (verifyDeviceSession(provided, policy.sessionSecret, now) || (authenticated && provided?.startsWith('v1.'))) {+ authFailures.delete(bucket)+ writeSessionRedirect(response, policy, url.pathname, now)+ return false+ }+ if (authenticated)return trueconst banned = rateLimitBlockedMs(authFailures.get(bucket), now)if (banned > 0) {writeAuthChallenge(request, response, BANNED_REASON, 429, banned)return false}- const url = new URL(request.url ?? '/', 'http://gateway.invalid')if (request.method === 'GET' && url.pathname === '/' && url.searchParams.has(AUTH_QUERY)) {- const provided = url.searchParams.get(AUTH_QUERY) ?? undefinedif (tokenMatches(provided, policy.linkToken) || (provided !== undefined && (policy.consumePairingCode?.(provided) ?? tokenMatches(provided, policy.pairingCode ?? null)))) {authFailures.delete(bucket)writeSessionRedirect(response, policy, url.pathname, now)@@ -332,7 +380,7 @@ async function admitAuthenticated(entry: GatewayEntry, request: IncomingMessage,const completedAt = Date.now()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)+ writeSessionRedirect(response, latest, pairing ? '/' : `${url.pathname}${url.search}`, completedAt)return false}failAuth(bucket, completedAt, request, response, '配对码不正确或已失效。')@@ -434,6 +482,8 @@ async function forward(entry: GatewayEntry, request: IncomingMessage, response:}function sendUpstream(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, headers: OutgoingHttpHeaders, attempt: ForwardAttempt, source: RemoteSourceClass): Promise<void> {+ if (request.socket.destroyed || response.destroyed)+ return Promise.resolve()return new Promise((resolve) => {const upstream = httpRequest({host: entry.upstream.hostname,diff --git a/packages/dsh-tauri-remote/src/host/utils/auth.test.ts b/packages/dsh-tauri-remote/src/host/utils/auth.test.tsindex 3c08a041..707ae771 100644--- a/packages/dsh-tauri-remote/src/host/utils/auth.test.ts+++ b/packages/dsh-tauri-remote/src/host/utils/auth.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { createLinkToken, createSessionSecret, rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifySession } from './auth'+import { createLinkToken, createSessionSecret, rateLimitAfterFailure, rateLimitBlockedMs, signDeviceSession, signSession, tokenMatches, verifyDeviceSession, verifySession } from './auth'const FAILURE_LIMIT = 5@@ -43,6 +43,31 @@ describe('signSession / verifySession', () => {})})+describe('device sessions', () => {+ it('keeps signed device authorization past cookie expiry without accepting it as a cookie', () => {+ const ticket = signDeviceSession(SESSION_SECRET, ISSUED_AT)+ expect(ticket.issuedAt).toBe(ISSUED_AT)+ expect(ticket.expiresAt).toBe(0)+ expect(verifyDeviceSession(ticket.value, SESSION_SECRET, ISSUED_AT)).toBe(true)+ expect(verifyDeviceSession(ticket.value, SESSION_SECRET, EXPIRES_AT + 365 * 24 * 60 * 60 * 1000)).toBe(true)+ expect(verifySession(ticket.value, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifyDeviceSession(SESSION_VALUE, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifyDeviceSession(ticket.value, 'rotated-secret', ISSUED_AT)).toBe(false)+ expect(verifyDeviceSession(ticket.value.replace(`.${ISSUED_AT}.`, `.${ISSUED_AT + 1}.`), SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifyDeviceSession(ticket.value.replace('.0.', `.${EXPIRES_AT}.`), SESSION_SECRET, ISSUED_AT)).toBe(false)+ })++ it('rejects malformed or unsafe signed timestamps in both ticket types', () => {+ for (const issuedAt of [-1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {+ expect(verifySession(signSession(SESSION_SECRET, issuedAt, EXPIRES_AT).value, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifyDeviceSession(signDeviceSession(SESSION_SECRET, issuedAt).value, SESSION_SECRET, ISSUED_AT)).toBe(false)+ }+ for (const value of [undefined, '', 'v1.1.0.x', 'v2.1.0.x'])+ expect(verifyDeviceSession(value, SESSION_SECRET, ISSUED_AT)).toBe(false)+ expect(verifySession(signSession(SESSION_SECRET, ISSUED_AT, Number.MAX_SAFE_INTEGER).value, SESSION_SECRET, ISSUED_AT)).toBe(false)+ })+})+describe('createSessionSecret', () => {it('generates independent 32-byte base64url secrets', () => {const first = createSessionSecret()diff --git a/packages/dsh-tauri-remote/src/host/utils/auth.ts b/packages/dsh-tauri-remote/src/host/utils/auth.tsindex bd7da947..0ba84a54 100644--- a/packages/dsh-tauri-remote/src/host/utils/auth.ts+++ b/packages/dsh-tauri-remote/src/host/utils/auth.ts@@ -17,11 +17,26 @@ const LINK_TOKEN_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'const SESSION_VERSION = 'v1'export function signSession(secret: string, now: number, ttlMs = SESSION_TTL_MS): RemoteSessionTicket {- const expiresAt = now + ttlMs- return { value: `${SESSION_VERSION}.${now}.${expiresAt}.${signatureOf(secret, now, expiresAt)}`, issuedAt: now, expiresAt }+ return signTicket(secret, now, now + ttlMs)+}++export function signDeviceSession(secret: string, now: number): RemoteSessionTicket {+ return signTicket(secret, now, 0)}export function verifySession(value: string | undefined, secret: string, now: number): boolean {+ return verifyTicket(value, secret, now, false)+}++export function verifyDeviceSession(value: string | undefined, secret: string, now: number): boolean {+ return verifyTicket(value, secret, now, true)+}++function signTicket(secret: string, issuedAt: number, expiresAt: number): RemoteSessionTicket {+ return { value: `${SESSION_VERSION}.${issuedAt}.${expiresAt}.${signatureOf(secret, issuedAt, expiresAt)}`, issuedAt, expiresAt }+}++function verifyTicket(value: string | undefined, secret: string, now: number, device: boolean): boolean {if (value === undefined || secret === '')return falseconst segments = value.split('.')@@ -29,8 +44,11 @@ export function verifySession(value: string | undefined, secret: string, now: nuconst issuedAt = Number(segments[1])const expiresAt = Number(segments[2])const mac = segments[3]- if (segments.length !== 4 || version !== SESSION_VERSION || mac === undefined || !Number.isInteger(issuedAt) || !Number.isInteger(expiresAt) || expiresAt <= now)+ if (segments.length !== 4 || version !== SESSION_VERSION || mac === undefined+ || !Number.isSafeInteger(issuedAt) || issuedAt < 0 || !Number.isSafeInteger(expiresAt)+ || (device ? expiresAt !== 0 : expiresAt <= now || expiresAt <= issuedAt)) {return false+ }return matches(Buffer.from(signatureOf(secret, issuedAt, expiresAt)), Buffer.from(mac))}diff --git a/src-native/app/index.tsx b/src-native/app/index.tsxindex f4084294..53081d7d 100644--- a/src-native/app/index.tsx+++ b/src-native/app/index.tsx@@ -53,7 +53,7 @@ function ConnectionDrawer() {{ text: t('common.cancel'), style: 'cancel' },{ text: t('connection.delete'), style: 'destructive', onPress: () => {stopConnectionRuntime()- connection.remove(entry.id)+ connection.forget(entry.id)} },])} },diff --git a/src-native/config/constants.ts b/src-native/config/constants.tsindex 79db2980..d5ce456f 100644--- a/src-native/config/constants.ts+++ b/src-native/config/constants.ts@@ -8,6 +8,7 @@ export const HEALTH_INTERVAL_MS = 15000export const HISTORY_LIMIT = 20export const RECENT_LIMIT = 5export const WEBVIEW_LOAD_TIMEOUT_MS = 20000+export const SESSION_FORGET_TIMEOUT_MS = 2000export const FOCUS_RETRY_INTERVAL_MS = 200export const FOCUS_TIMEOUT_MS = 15000export const NOTIFICATION_CHANNEL = 'dsh-bridge'diff --git a/src-native/store/modules/connection/index.test.ts b/src-native/store/modules/connection/index.test.tsindex 2497298d..e1f04977 100644--- a/src-native/store/modules/connection/index.test.ts+++ b/src-native/store/modules/connection/index.test.ts@@ -8,6 +8,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItemconst alpha: BridgeAddress = { id: 'http://bridge.local:3080', url: 'http://bridge.local:3080/tasks?theme=dark', host: 'bridge.local', port: 3080 }const beta: BridgeAddress = { id: 'https://second.local', url: 'https://second.local/workspaces', host: 'second.local', port: 443 }+const deviceToken = `v1.1700000000000.0.${'a'.repeat(64)}`function load(address: BridgeAddress, at: number) {expect(connection.accept(address)).toBe(true)@@ -116,6 +117,29 @@ describe('parseConnectionSnapshot trust boundary', () => {})describe('connection editing', () => {+ it('forgets saved metadata immediately even if cookie clearing is interrupted by a different connection', () => {+ load(alpha, 10)+ connection.markHydrated({ [alpha.id]: 'secret' })+ connection.dismissHint()+ connection.queueFocus({ origin: alpha.id, sessionId: 's1', title: 'Task', tag: 'task' })+ const generation = connection.viewGeneration+ connection.forget(alpha.id)+ expect(connection.current).toEqual(alpha)+ expect(connection.forgettingOrigin).toBe(alpha.id)+ expect(connection.viewGeneration).toBe(generation)+ expect(connection.history).toEqual([])+ expect(connection.guidedHosts).toEqual([])+ expect(connection.health).toEqual({})+ expect(connection.tokens).toEqual({})+ expect(connection.pendingFocus).toBeNull()+ expect(connection.accept(alpha)).toBe(false)+ connection.disconnect()+ expect(connection.accept(beta)).toBe(true)+ expect(connection.accept(alpha)).toBe(true)+ expect(connection.current).toEqual(alpha)+ expect(connection.history).toEqual([])+ })+it('keeps a trimmed display name through reconnect, load and snapshot restoration without changing the URL', () => {load(alpha, 10)const generation = connection.viewGeneration@@ -190,6 +214,7 @@ describe('connection hydration', () => {viewGeneration: 0,pendingFocus: null,focusGeneration: 0,+ forgettingOrigin: null,})connection.setHealth('http://bridge.local:3080', 'unavailable')expect(connection.health).toEqual({ 'http://bridge.local:3080': 'unavailable' })@@ -257,7 +282,8 @@ describe('connection scan and view generations', () => {})it('beginScan clears transient view state while retaining successful history and tokens', () => {- load({ ...alpha, token: 'saved' }, 10)+ load(alpha, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)connection.setDrawerOpen(true)connection.setNotice('old notice')connection.markLoadFailed(connection.viewGeneration, 'old error')@@ -271,7 +297,7 @@ describe('connection scan and view generations', () => {expect(connection.drawerOpen).toBe(false)expect(connection.swipeHintVisible).toBe(false)expect(connection.history).toEqual([{ ...alpha, lastConnectedAt: 10 }])- expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'saved' })+ expect(connection.tokens).toEqual({ 'http://bridge.local:3080': deviceToken })})it('ignores stale loaded and failed callbacks after accepting another origin', () => {@@ -302,7 +328,7 @@ describe('connection acceptance and successful history', () => {it('normalizes the URL instead of trusting id, host and port supplied by a caller', () => {expect(connection.accept({ id: 'https://evil.local', url: 'http://BRIDGE.local:80/tasks?token=url-secret&theme=dark#fragment', host: 'evil.local', port: 9, token: 'explicit-secret' })).toBe(true)expect(connection.current).toEqual({ id: 'http://bridge.local', url: 'http://bridge.local/tasks?theme=dark', host: 'bridge.local', port: 80, token: 'explicit-secret' })- expect(connection.tokens).toEqual({ 'http://bridge.local': 'explicit-secret' })+ expect(connection.tokens).toEqual({})expect(connection.history).toEqual([])expect(connection.health).toEqual({ 'http://bridge.local': 'available' })})@@ -316,17 +342,17 @@ describe('connection acceptance and successful history', () => {expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'saved' })})- it('remembers a token extracted from the accepted URL even if there was no explicit token field', () => {+ it('uses a token extracted from the accepted URL transiently without persisting it', () => {connection.accept({ ...alpha, url: 'http://bridge.local:3080/tasks?auth=fresh&theme=dark' })expect(connection.current).toEqual({ ...alpha, token: 'fresh' })- expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'fresh' })+ expect(connection.tokens).toEqual({})})it('prefers a newly scanned URL token over an older saved token for that origin', () => {connection.markHydrated({ 'http://bridge.local:3080': 'old' })connection.accept({ ...alpha, url: 'http://bridge.local:3080/tasks?auth=fresh&theme=dark' })expect(connection.current).toEqual({ ...alpha, token: 'fresh' })- expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'fresh' })+ expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'old' })})it('records history only after a successful view load', () => {@@ -428,7 +454,8 @@ describe('connection hints, disconnect and serialization', () => {})it('disconnect clears transient UI and invalidates callbacks while preserving history, secure tokens and guides', () => {- load({ ...alpha, token: 'secure-secret' }, 10)+ load(alpha, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)connection.dismissHint()connection.setDrawerOpen(true)connection.setNotice('offline')@@ -448,7 +475,7 @@ describe('connection hints, disconnect and serialization', () => {expect(connection.swipeHintVisible).toBe(false)expect(connection.pendingFocus).toBeNull()expect(connection.history).toEqual([{ ...alpha, lastConnectedAt: 10 }])- expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'secure-secret' })+ expect(connection.tokens).toEqual({ 'http://bridge.local:3080': deviceToken })expect(connection.guidedHosts).toEqual(['http://bridge.local:3080'])})diff --git a/src-native/store/modules/connection/index.ts b/src-native/store/modules/connection/index.tsindex 30d8866d..9edce72d 100644--- a/src-native/store/modules/connection/index.ts+++ b/src-native/store/modules/connection/index.ts@@ -4,7 +4,7 @@ import { defineStore } from 'valtio-define'import { persist } from 'valtio-define/plugins/persist'import { CONNECTION_STORAGE_KEY, HISTORY_LIMIT, RECENT_LIMIT } from '@/config/constants'import { i18n } from '@/i18n'-import { isRecord, parseQrPayload } from '@/utils/bridge-protocol'+import { isDeviceSession, isRecord, parseQrPayload } from '@/utils/bridge-protocol'export type ConnectionStage = 'scanning' | 'idle' | 'connected'export type HostHealth = 'checking' | 'available' | 'unavailable'@@ -44,6 +44,7 @@ export interface ConnectionState {viewGeneration: numberpendingFocus: NotificationFocus | nullfocusGeneration: number+ forgettingOrigin: string | null}/** 持久化字段:插件按此顺序把 state 写成 `{version, history, guidedHosts}`。 */@@ -182,6 +183,7 @@ export function createConnectionState(): ConnectionState {viewGeneration: 0,pendingFocus: null,focusGeneration: 0,+ forgettingOrigin: null,}}@@ -210,6 +212,7 @@ export const connection = defineStore({this.notice = nullthis.drawerOpen = falsethis.swipeHintVisible = false+ this.forgettingOrigin = nullreturn this.scanGeneration},cancelScan() {@@ -227,7 +230,7 @@ export const connection = defineStore({if (generation !== undefined && generation !== this.scanGeneration)return falseconst normalized = parseQrPayload(address.url)- if (!normalized)+ if (!normalized || normalized.id === this.forgettingOrigin)return falselet name = this.history.find(entry => entry.id === normalized.id)?.nameif (!name && this.current?.id === normalized.id)@@ -235,10 +238,8 @@ export const connection = defineStore({if (name)normalized.name = nameconst token = address.token ?? normalized.token ?? this.tokens[normalized.id]- if (token) {+ if (token)normalized.token = token- this.tokens[normalized.id] = token- }this.scanGeneration++this.current = normalizedthis.stage = 'connected'@@ -248,6 +249,7 @@ export const connection = defineStore({this.drawerOpen = falsethis.swipeHintVisible = falsethis.health[normalized.id] = 'available'+ this.forgettingOrigin = nullthis.viewGeneration++return true},@@ -265,6 +267,14 @@ export const connection = defineStore({this.swipeHintVisible = !this.guidedHosts.includes(id)this.health[id] = 'available'},+ rememberDeviceSession(origin: string, token: string, generation: number) {+ if (generation !== this.viewGeneration || this.current?.id !== origin || this.loading || this.loadError+ || this.forgettingOrigin === origin || !isDeviceSession(token)) {+ return+ }+ this.tokens[origin] = token+ this.current.token = token+ },markLoadFailed(generation: number, message: string) {if (!this.current || generation !== this.viewGeneration)return@@ -303,6 +313,20 @@ export const connection = defineStore({if (this.current?.id === id)this.current.name = trimmed},+ forget(id: string) {+ if (this.current?.id !== id) {+ this.remove(id)+ return+ }+ this.history = this.history.filter(entry => entry.id !== id)+ this.guidedHosts = this.guidedHosts.filter(origin => origin !== id)+ delete this.tokens[id]+ delete this.health[id]+ delete this.current.token+ if (this.pendingFocus?.origin === id)+ this.queueFocus(null)+ this.forgettingOrigin = id+ },remove(id: string) {if (this.current?.id === id)this.disconnect('idle')@@ -324,6 +348,7 @@ export const connection = defineStore({this.drawerOpen = falsethis.swipeHintVisible = falsethis.pendingFocus = null+ this.forgettingOrigin = null},/** 当前应当落盘的快照(含归一化),磁盘格式与旧版实现一致。 */serialize(): ConnectionSnapshot {diff --git a/src-native/store/modules/connection/runtime.test.ts b/src-native/store/modules/connection/runtime.test.tsindex f782f197..6c5c0956 100644--- a/src-native/store/modules/connection/runtime.test.ts+++ b/src-native/store/modules/connection/runtime.test.ts@@ -154,7 +154,7 @@ function describeDirectConnections() {runtime.connectAddress({ ...alpha, token: 'fixture-new-token' })expect(connection.current).toEqual({ ...alpha, token: 'fixture-new-token' })- expect(connection.tokens).toEqual({ 'http://10.0.0.20:4444': 'fixture-new-token' })+ expect(connection.tokens).toEqual({ 'http://10.0.0.20:4444': 'fixture-old-token' })expect(connection.serialize()).toEqual({ version: 1, history: [], guidedHosts: [] })}@@ -166,7 +166,7 @@ function describeDirectConnections() {runtime.connectAddress({ ...alpha, url: 'http://10.0.0.20:4444/tasks?auth=fixture-new-token&theme=dark' })expect(connection.current).toEqual({ ...alpha, token: 'fixture-new-token' })- expect(connection.tokens).toEqual({ 'http://10.0.0.20:4444': 'fixture-new-token' })+ expect(connection.tokens).toEqual({ 'http://10.0.0.20:4444': 'fixture-old-token' })}it('aborts an in-flight history probe before a direct connection and ignores its late success', supersedeHistoryWithDirectConnection)diff --git a/src-native/store/modules/connection/storage.test.ts b/src-native/store/modules/connection/storage.test.tsindex 1e05238f..49e9e4ab 100644--- a/src-native/store/modules/connection/storage.test.ts+++ b/src-native/store/modules/connection/storage.test.ts@@ -18,6 +18,8 @@ vi.mock('expo-localization', () => ({ getLocales: () => [{ languageTag: 'zh-CN'const alpha = { id: 'http://bridge.local:3080', url: 'http://bridge.local:3080/tasks?theme=dark', host: 'bridge.local', port: 3080 }const beta = { id: 'https://second.local', url: 'https://second.local/workspaces', host: 'second.local', port: 443 }+const deviceToken = `v1.1700000000000.0.${'a'.repeat(64)}`+const betaDeviceToken = `v1.1700000000001.0.${'b'.repeat(64)}`const alphaKey = 'dsh-bridge.token.0068007400740070003a002f002f006200720069006400670065002e006c006f00630061006c003a0033003000380030'const betaKey = 'dsh-bridge.token.00680074007400700073003a002f002f007300650063006f006e0064002e006c006f00630061006c'const emptySnapshot: ConnectionSnapshot = { version: 1, history: [], guidedHosts: [] }@@ -84,9 +86,56 @@ afterEach(() => {vi.useRealTimers()})+describe('paired device authorization', () => {+ it('keeps the input pairing code transient and persists only authorization received from the verified document', async () => {+ await hydrate()+ bind()+ connection.accept({ ...alpha, token: 'AB23CD45' })+ await vi.advanceTimersByTimeAsync(0)+ expect(connection.tokens).toEqual({})+ expect(native.writeToken).not.toHaveBeenCalled()+ connection.markLoaded(connection.viewGeneration, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)+ await vi.advanceTimersByTimeAsync(0)+ expect(native.writeToken).toHaveBeenCalledExactlyOnceWith(alphaKey, deviceToken)+ expect(connection.current?.token).toBe(deviceToken)+ expect(writtenPayloads().every(value => !value.includes(deviceToken) && !value.includes('AB23CD45'))).toBe(true)+ })++ it('does not replace authorization from a stale, foreign, failed, loading or forgetting document', async () => {+ await hydrate()+ connection.accept(alpha)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)+ expect(connection.tokens).toEqual({})+ connection.markLoaded(connection.viewGeneration, 10)+ connection.rememberDeviceSession(beta.id, deviceToken, connection.viewGeneration)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration - 1)+ connection.rememberDeviceSession(alpha.id, 'AB23CD45', connection.viewGeneration)+ expect(connection.tokens).toEqual({})+ connection.markLoadFailed(connection.viewGeneration, 'network error')+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)+ expect(connection.tokens).toEqual({})+ connection.accept(alpha)+ connection.markLoaded(connection.viewGeneration, 20)+ connection.forget(alpha.id)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)+ expect(connection.tokens).toEqual({})+ })++ it('restores a reusable device ticket for reconnection but deletes a previously saved temporary pairing code', async () => {+ native.read.mockResolvedValue(payload([{ ...alpha, lastConnectedAt: 10 }, { ...beta, lastConnectedAt: 5 }]))+ native.readToken.mockImplementation(async key => key === alphaKey ? deviceToken : 'AB23CD45')+ await restoreConnections()+ expect(connection.tokens).toEqual({ [alpha.id]: deviceToken })+ expect(native.deleteToken).toHaveBeenCalledExactlyOnceWith(betaKey)+ connection.accept(alpha)+ expect(connection.current?.token).toBe(deviceToken)+ })+})+describe('connection editing persistence', () => {it('persists a renamed host and deletes its secure token when the active connection is removed', async () => {- await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [alpha.id] }, { [alpha.id]: 'secret' })+ await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [alpha.id] }, { [alpha.id]: deviceToken })bind()connection.accept(alpha)connection.rename(alpha.id, '我的电脑')@@ -113,7 +162,7 @@ describe('restoreConnections', () => {}))native.readToken.mockImplementation(async (key) => {if (key === alphaKey)- return 'secure-alpha'+ return deviceTokenif (key === betaKey)return nullthrow new Error(`Unexpected secure key: ${key}`)@@ -123,7 +172,7 @@ describe('restoreConnections', () => {expect(native.readToken.mock.calls).toEqual([[betaKey], [alphaKey]])expect(connection.hydrated).toBe(true)expect(connection.history).toEqual([{ ...beta, lastConnectedAt: 20 }, { ...alpha, lastConnectedAt: 10 }])- expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'secure-alpha' })+ expect(connection.tokens).toEqual({ 'http://bridge.local:3080': deviceToken })expect(connection.guidedHosts).toEqual(['http://bridge.local:3080'])expect(connection.current).toBeNull()expect(connection.stage).toBe('idle')@@ -244,7 +293,7 @@ describe('restoreConnections', () => {native.readToken.mockImplementation(async (key) => {if (key === betaKey)throw error- return 'secure-alpha'+ return deviceToken})await restoreConnections()expect(connection.serialize()).toEqual({@@ -252,7 +301,7 @@ describe('restoreConnections', () => {history: [{ ...beta, lastConnectedAt: 20 }, { ...alpha, lastConnectedAt: 10 }],guidedHosts: [alpha.id],})- expect(connection.tokens).toEqual({ [alpha.id]: 'secure-alpha' })+ expect(connection.tokens).toEqual({ [alpha.id]: deviceToken })expect(connection.notice).toBe(storageFailure)expect(log).toHaveBeenCalledExactlyOnceWith('[connection] token restore failed:', error)expect(native.write).not.toHaveBeenCalled()@@ -280,12 +329,12 @@ describe('restoreConnections', () => {expect(connection.history).toEqual([{ ...alpha, lastConnectedAt: 10 }])expect(connection.tokens).toEqual({})expect(native.write).not.toHaveBeenCalled()- tokenRead.resolve('secure-alpha')+ tokenRead.resolve(deviceToken)await restoringawait vi.advanceTimersByTimeAsync(0)expect(connection.hydrated).toBe(true)- expect(connection.tokens).toEqual({ [alpha.id]: 'secure-alpha' })- expect(native.writeToken).toHaveBeenCalledExactlyOnceWith(alphaKey, 'secure-alpha')+ expect(connection.tokens).toEqual({ [alpha.id]: deviceToken })+ expect(native.writeToken).toHaveBeenCalledExactlyOnceWith(alphaKey, deviceToken)expect(native.write).not.toHaveBeenCalled()expect(native.deleteToken).not.toHaveBeenCalled()})@@ -337,31 +386,34 @@ describe('bindConnectionPersistence security and ordering', () => {expect(native.deleteToken).not.toHaveBeenCalled()})- it('retains the current unsaved token in secure storage without putting it in the public snapshot', async () => {+ it('retains verified device authorization in secure storage without putting it in the public snapshot', async () => {await hydrate()bind()connection.accept({ ...alpha, token: 'current-secret' })await vi.advanceTimersByTimeAsync(0)- expect(native.writeToken).toHaveBeenCalledExactlyOnceWith(alphaKey, 'current-secret')- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'current-secret']])+ expect(native.writeToken).not.toHaveBeenCalled()expect(native.write).not.toHaveBeenCalled()connection.markLoaded(connection.viewGeneration, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)await vi.advanceTimersByTimeAsync(0)+ expect(native.writeToken).toHaveBeenCalledExactlyOnceWith(alphaKey, deviceToken)expect(native.write).toHaveBeenCalledExactlyOnceWith('dsh-bridge/connections', payload([{ ...alpha, lastConnectedAt: 10 }]))expect(writtenPayloads()[0]).not.toContain('current-secret')- expect(connection.tokens).toEqual({ [alpha.id]: 'current-secret' })+ expect(writtenPayloads()[0]).not.toContain(deviceToken)+ expect(connection.tokens).toEqual({ [alpha.id]: deviceToken })expect(native.deleteToken).not.toHaveBeenCalled()})it('writes only retained-origin tokens and excludes secrets from successful history serialization', async () => {await hydrate()- connection.$patch({ tokens: { 'http://orphan.local': 'orphan-secret' } })+ connection.$patch({ tokens: { 'http://orphan.local': betaDeviceToken } })bind()connection.accept({ ...alpha, url: 'http://bridge.local:3080/tasks?auth=qr-secret&token=other&theme=dark#private', token: 'secure-secret' })connection.markLoaded(connection.viewGeneration, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)connection.dismissHint()await vi.advanceTimersByTimeAsync(0)- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'secure-secret']])+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken]])expect(native.write).toHaveBeenCalledExactlyOnceWith('dsh-bridge/connections', payload([{ ...alpha, lastConnectedAt: 10 }], ['http://bridge.local:3080']))expect(native.write.mock.calls[0]?.[1]).not.toContain('secret')expect(native.write.mock.calls[0]?.[1]).not.toContain('auth')@@ -373,34 +425,36 @@ describe('bindConnectionPersistence security and ordering', () => {native.write.mockReturnValueOnce(firstWrite.promise)await hydrate()bind()- connection.accept({ ...alpha, token: 'alpha-secret' })+ connection.accept(alpha)connection.markLoaded(connection.viewGeneration, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)await vi.advanceTimersByTimeAsync(0)expect(native.write).toHaveBeenCalledTimes(1)- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'alpha-secret']])- connection.accept({ ...beta, token: 'beta-secret' })+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken]])+ connection.accept(beta)connection.markLoaded(connection.viewGeneration, 20)+ connection.rememberDeviceSession(beta.id, betaDeviceToken, connection.viewGeneration)await vi.advanceTimersByTimeAsync(0)expect(native.write).toHaveBeenCalledTimes(1)expect(JSON.parse(native.write.mock.calls[0]![1])).toEqual({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [] })- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'alpha-secret'], [alphaKey, 'alpha-secret'], [betaKey, 'beta-secret']])+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken], [alphaKey, deviceToken], [betaKey, betaDeviceToken]])firstWrite.resolve(undefined)await vi.advanceTimersByTimeAsync(0)expect(native.write.mock.calls.map(call => [call[0], JSON.parse(call[1])])).toEqual([['dsh-bridge/connections', { version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [] }],['dsh-bridge/connections', { version: 1, history: [{ ...beta, lastConnectedAt: 20 }, { ...alpha, lastConnectedAt: 10 }], guidedHosts: [] }],])- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'alpha-secret'], [alphaKey, 'alpha-secret'], [betaKey, 'beta-secret']])+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken], [alphaKey, deviceToken], [betaKey, betaDeviceToken]])})it('writes the pruned history and deletes the secure token of an evicted origin without waiting for the snapshot write', async () => {const snapshotWrite = deferred<void>()native.write.mockReturnValueOnce(snapshotWrite.promise)- await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }, { ...beta, lastConnectedAt: 5 }], guidedHosts: [] }, { 'http://bridge.local:3080': 'alpha-secret', 'https://second.local': 'beta-secret' })+ await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }, { ...beta, lastConnectedAt: 5 }], guidedHosts: [] }, { 'http://bridge.local:3080': deviceToken, 'https://second.local': betaDeviceToken })bind()connection.$patch({ history: [{ ...beta, lastConnectedAt: 5 }] })await vi.advanceTimersByTimeAsync(0)- expect(native.writeToken.mock.calls).toEqual([[betaKey, 'beta-secret']])+ expect(native.writeToken.mock.calls).toEqual([[betaKey, betaDeviceToken]])expect(native.write).toHaveBeenCalledExactlyOnceWith('dsh-bridge/connections', payload([{ ...beta, lastConnectedAt: 5 }]))expect(native.deleteToken).toHaveBeenCalledExactlyOnceWith(alphaKey)expect(native.write.mock.invocationCallOrder[0]).toBeLessThan(native.deleteToken.mock.invocationCallOrder[0]!)@@ -409,17 +463,17 @@ describe('bindConnectionPersistence security and ordering', () => {expect(native.deleteToken).toHaveBeenCalledExactlyOnceWith(alphaKey)})- it('keeps saved history tokens on disconnect while deleting a token for an unsaved current origin', async () => {- await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [] }, { 'http://bridge.local:3080': 'alpha-secret' })+ it('keeps saved device authorization on disconnect without saving an unverified current pairing code', async () => {+ await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [] }, { 'http://bridge.local:3080': deviceToken })bind()connection.accept({ ...beta, token: 'unsaved-secret' })await vi.advanceTimersByTimeAsync(0)- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'alpha-secret'], [betaKey, 'unsaved-secret']])+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken]])connection.disconnect()await vi.advanceTimersByTimeAsync(0)expect(connection.history).toEqual([{ ...alpha, lastConnectedAt: 10 }])- expect(native.deleteToken.mock.calls).toEqual([[betaKey]])- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'alpha-secret'], [betaKey, 'unsaved-secret'], [alphaKey, 'alpha-secret']])+ expect(native.deleteToken).not.toHaveBeenCalled()+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken], [alphaKey, deviceToken]])expect(native.write).not.toHaveBeenCalled()})@@ -503,23 +557,22 @@ describe('connection persistence failures', () => {native.writeToken.mockRejectedValueOnce(error)await hydrate()bind()- connection.accept({ ...alpha, token: 'secure-secret' })+ connection.accept(alpha)+ connection.markLoaded(connection.viewGeneration, 10)+ connection.rememberDeviceSession(alpha.id, deviceToken, connection.viewGeneration)await vi.advanceTimersByTimeAsync(0)expect(log).toHaveBeenCalledExactlyOnceWith('[connection] token save failed:', error)expect(connection.notice).toBe(storageFailure)- expect(native.writeToken.mock.calls).toEqual([[alphaKey, 'secure-secret'], [alphaKey, 'secure-secret']])- expect(native.write).not.toHaveBeenCalled()- connection.markLoaded(connection.viewGeneration, 10)- await vi.advanceTimersByTimeAsync(0)+ expect(native.writeToken.mock.calls).toEqual([[alphaKey, deviceToken], [alphaKey, deviceToken]])expect(native.write).toHaveBeenCalledExactlyOnceWith('dsh-bridge/connections', payload([{ ...alpha, lastConnectedAt: 10 }]))- expect(writtenPayloads()[0]).not.toContain('secure-secret')+ expect(writtenPayloads()[0]).not.toContain(deviceToken)})it('reports a secure deletion failure and retries the eviction on the next persistence sync', async () => {const error = new Error('Secure delete refused')const log = vi.spyOn(console, 'error').mockImplementation(() => {})native.deleteToken.mockRejectedValueOnce(error)- await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [] }, { 'http://bridge.local:3080': 'secure-secret' })+ await hydrate({ version: 1, history: [{ ...alpha, lastConnectedAt: 10 }], guidedHosts: [] }, { 'http://bridge.local:3080': deviceToken })bind()connection.$patch({ history: [] })await vi.advanceTimersByTimeAsync(0)diff --git a/src-native/store/modules/connection/storage.ts b/src-native/store/modules/connection/storage.tsindex 3b72e823..a4bb35a7 100644--- a/src-native/store/modules/connection/storage.ts+++ b/src-native/store/modules/connection/storage.ts@@ -1,5 +1,6 @@import * as SecureStore from 'expo-secure-store'import { i18n } from '@/i18n'+import { isDeviceSession } from '@/utils/bridge-protocol'import { connection } from './index'function tokenKey(origin: string): string {@@ -27,7 +28,9 @@ export async function restoreConnections(): Promise<void> {const entries = await Promise.all(connection.history.map(async (entry) => {try {const token = await SecureStore.getItemAsync(tokenKey(entry.id))- return [entry.id, token] as const+ if (token && !isDeviceSession(token))+ await SecureStore.deleteItemAsync(tokenKey(entry.id))+ return [entry.id, isDeviceSession(token) ? token : null] as const}catch (error) {console.error('[connection] token restore failed:', error)@@ -57,8 +60,8 @@ export function bindConnectionPersistence(): () => void {const retained = new Set(connection.history.map(entry => entry.id))if (connection.current)retained.add(connection.current.id)- const tokens = Object.fromEntries(Object.entries(connection.tokens).filter(([id]) => retained.has(id)))- const payload = JSON.stringify(tokens)+ const tokens = Object.fromEntries(Object.entries(connection.tokens).filter(([id, token]) => retained.has(id) && isDeviceSession(token)))+ const payload = JSON.stringify({ tokens, retained: [...retained].sort() })if (payload === lastPayload)returnlastPayload = payload@@ -66,10 +69,10 @@ export function bindConnectionPersistence(): () => void {for (const [id, token] of Object.entries(tokens))await SecureStore.setItemAsync(tokenKey(id), token)for (const id of writtenIds) {- if (!retained.has(id))+ if (!tokens[id])await SecureStore.deleteItemAsync(tokenKey(id))}- writtenIds = retained+ writtenIds = new Set(Object.keys(tokens))}).catch((error) => {lastPayload = ''console.error('[connection] token save failed:', error)diff --git a/src-native/ui/_layout.test.tsx b/src-native/ui/_layout.test.tsxindex 973d7e2c..856f4a9a 100644--- a/src-native/ui/_layout.test.tsx+++ b/src-native/ui/_layout.test.tsx@@ -198,6 +198,7 @@ vi.mock('react-native-webview', async () => {const alpha = { id: 'http://bridge.local:3080', url: 'http://bridge.local:3080/tasks', host: 'bridge.local', port: 3080 }const beta = { id: 'https://second.local', url: 'https://second.local/workspaces', host: 'second.local', port: 443 }+const deviceToken = `v1.1700000000000.0.${'a'.repeat(64)}`const snapshot = { version: 1 as const, history: [{ ...alpha, lastConnectedAt: 20 }, { ...beta, lastConnectedAt: 10 }], guidedHosts: ['http://bridge.local:3080', 'https://second.local'] }let screen: ReactTestRenderer | undefinedlet store: typeof import('@/store/modules/connection')@@ -467,12 +468,12 @@ describe('rendered root hydration', () => {expect(native.fetch).not.toHaveBeenCalled()expect(native.write).not.toHaveBeenCalled()await act(async () => {- tokenRead.resolve('secure-token')+ tokenRead.resolve(deviceToken)await vi.advanceTimersByTimeAsync(0)})expect(drawer().props.swipeEnabled).toBe(true)- expect(webView().props.source).toEqual({ uri: 'http://bridge.local:3080/tasks?auth=secure-token' })+ expect(webView().props.source).toEqual({ uri: `http://bridge.local:3080/?auth=${deviceToken}` })expect(texts()).toContain('连接中…')expect(native.read).toHaveBeenCalledExactlyOnceWith('dsh-bridge/connections')expect(native.getIpAddressAsync).not.toHaveBeenCalled()@@ -488,7 +489,7 @@ describe('rendered root hydration', () => {for (const [key, payload] of native.write.mock.calls) {expect(key).toBe('dsh-bridge/connections')expect(JSON.parse(payload)).toEqual({ version: 1, history: [{ ...alpha, lastConnectedAt: 30 }], guidedHosts: [] })- expect(payload).not.toContain('secure-token')+ expect(payload).not.toContain(deviceToken)}})})@@ -629,7 +630,7 @@ describe('rendered root notification focus', () => {expect(native.dismissTo).not.toHaveBeenCalled()expect(native.fetch).not.toHaveBeenCalled()await act(async () => {- tokenRead.resolve('cold-secret')+ tokenRead.resolve(deviceToken)await vi.advanceTimersByTimeAsync(0)})@@ -637,7 +638,7 @@ describe('rendered root notification focus', () => {expect(texts()).not.toContain('扫码连接 DSH Mobile')expect(root().findAll(node => String(node.type) === 'CameraView')).toHaveLength(0)expect(drawer().props.open).toBe(false)- expect(webView().props.source).toEqual({ uri: 'http://bridge.local:3080/tasks?auth=cold-secret' })+ expect(webView().props.source).toEqual({ uri: `http://bridge.local:3080/?auth=${deviceToken}` })expect(native.getIpAddressAsync).not.toHaveBeenCalled()expect(connection.pendingFocus?.sessionId).toBe('cold-session')const instance = await webViewInstance()@@ -724,7 +725,7 @@ describe('rendered root notification focus', () => {expect(root().findAll(node => String(node.type) === 'CameraView')).toHaveLength(0)expect(connection.viewGeneration).toBe(1)expect(connection.history).toEqual([])- expect(webView().props.source).toEqual({ uri: 'http://bridge.local:3080/tasks' })+ expect(webView().props.source).toEqual({ uri: 'http://bridge.local:3080/?pair=1' })expect(connection.pendingFocus?.sessionId).toBe('pending-session')const instance = await webViewInstance()await ready('http://bridge.local:3080')diff --git a/src-native/ui/index.test.tsx b/src-native/ui/index.test.tsxindex e905f4a7..38163091 100644--- a/src-native/ui/index.test.tsx+++ b/src-native/ui/index.test.tsx@@ -293,7 +293,7 @@ describe('rendered Home scanning and idle actions', () => {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(webView().props.source).toEqual({ uri: `${origin}/?pair=1` })expect(connection.loading).toBe(true)expect(connection.history).toEqual([])expect(connection.notice).toBeNull()@@ -487,6 +487,14 @@ describe('rendered Home connection editing', () => {expect(root().findAll(node => String(node.type) === 'WebView')).toHaveLength(1)native.fetch.mockClear()await act(async () => confirmation[2]![1]!.onPress!())+ expect(connection.current?.id).toBe(alpha.id)+ expect(connection.forgettingOrigin).toBe(alpha.id)+ expect(connection.history.some(entry => entry.id === alpha.id)).toBe(false)+ expect(connection.tokens[alpha.id]).toBeUndefined()+ const generation = connection.viewGeneration+ await act(async () => runtime.connectAddress(alpha))+ expect(connection.viewGeneration).toBe(generation)+ await act(async () => vi.advanceTimersByTimeAsync(2000))expect(connection.current).toBeNull()expect(connection.stage).toBe('idle')expect(connection.history.some(entry => entry.id === alpha.id)).toBe(false)diff --git a/src-native/ui/scan.test.tsx b/src-native/ui/scan.test.tsxindex e70a9e1f..d883cf70 100644--- a/src-native/ui/scan.test.tsx+++ b/src-native/ui/scan.test.tsx@@ -331,7 +331,7 @@ describe('rendered scanner QR events', () => {expect(connection.current).toEqual({ id: 'http://bridge.local:3080', url: 'http://bridge.local:3080/tasks?theme=dark', host: 'bridge.local', port: 3080, token: 'qr-token' })expect(connection.stage).toBe('connected')- expect(connection.tokens).toEqual({ 'http://bridge.local:3080': 'qr-token' })+ expect(connection.tokens).toEqual({})expect(native.back).toHaveBeenCalledExactlyOnceWith()expect(camera().props.onBarcodeScanned).toBeUndefined()const generation = connection.viewGenerationdiff --git a/src-native/ui/webview.test.tsx b/src-native/ui/webview.test.tsxindex 50934d22..69223426 100644--- a/src-native/ui/webview.test.tsx+++ b/src-native/ui/webview.test.tsx@@ -322,6 +322,67 @@ afterEach(async () => {vi.useRealTimers()})+describe('rendered paired device authorization', () => {+ const token = `v1.1700000000000.0.${'a'.repeat(64)}`++ it('forces a new tokenless origin through pairing without persisting the pairing flag, while retaining remembered-host reconnects', async () => {+ await mount()+ expect(webView().props.source).toEqual({ uri: `${alpha.id}/?pair=1` })+ await ready()+ expect(connection.history[0]?.url).toBe(alpha.url)+ await unmount()+ runtime.connectAddress(alpha)+ await mount()+ expect(webView().props.source).toEqual({ uri: alpha.url })+ })++ it('requires pairing after forgetting even when switching hosts interrupts cookie clearing', async () => {+ await mount()+ await ready()+ await message({ type: 'dsh://device-session', token })+ await act(async () => connection.forget(alpha.id))+ expect(connection.tokens).toEqual({})+ expect(connection.history).toEqual([])+ const generation = connection.viewGeneration+ await act(async () => runtime.connectAddress(alpha))+ expect(connection.viewGeneration).toBe(generation)+ await unmount()+ runtime.connectAddress(beta)+ runtime.connectAddress(alpha)+ await mount()+ expect(webView().props.source).toEqual({ uri: `${alpha.id}/?pair=1` })+ })++ it('remembers authorization from the verified document without changing the initial WebView URI or generation', async () => {+ runtime.connectAddress({ ...alpha, token: 'AB23CD45' })+ await act(async () => {+ screen = create(createElement(BridgeWebView, { address: connection.current!, generation: connection.viewGeneration }))+ })+ const instance = await viewRef()+ const generation = connection.viewGeneration+ const source = webView().props.source+ await message({ type: 'dsh://device-session', token })+ expect(connection.tokens).toEqual({})+ await ready()+ await message({ type: 'dsh://device-session', token }, { nonce: 'stale-nonce' })+ await message({ type: 'dsh://device-session', token }, { url: beta.url })+ expect(connection.tokens).toEqual({})+ await message({ type: 'dsh://device-session', token })+ expect(connection.tokens).toEqual({ [alpha.id]: token })+ expect(connection.current?.token).toBe(token)+ await act(async () => {+ screen!.update(createElement(BridgeWebView, { address: connection.current!, generation }))+ })+ expect(webView().props.source).toEqual(source)+ expect(await viewRef()).toBe(instance)+ expect(connection.viewGeneration).toBe(generation)+ expect(native.scheduleNotificationAsync).not.toHaveBeenCalled()+ runtime.connectAddress(beta)+ await message({ type: 'dsh://device-session', token: `v1.1700000000001.0.${'b'.repeat(64)}` })+ expect(connection.tokens).toEqual({ [alpha.id]: token })+ })+})+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()@@ -724,7 +785,7 @@ describe('rendered Bridge WebView document lifecycle', () => {await mount()await act(async () => {await vi.advanceTimersByTimeAsync(20001)- webView().props[callback]({ nativeEvent: { url: alpha.url, code: -6, statusCode: 500, didCrash: true } })+ webView().props[callback]({ nativeEvent: { url: webView().props.source.uri, code: -6, statusCode: 500, didCrash: true } })})const page = createPage()await rawMessage(page.posts[0]!)@@ -764,7 +825,7 @@ describe('rendered Bridge WebView document lifecycle', () => {})expect(await viewRef()).not.toBe(oldView)- expect(webView().props.source).toEqual({ uri: 'https://second.test/workspaces' })+ expect(webView().props.source).toEqual({ uri: 'https://second.test/?pair=1' })expect(connection.current).toEqual(beta)expect(connection.loading).toBe(true)expect(connection.loadError).toBeNull()diff --git a/src-native/ui/webview.tsx b/src-native/ui/webview.tsxindex d28444dd..fea27aac 100644--- a/src-native/ui/webview.tsx+++ b/src-native/ui/webview.tsx@@ -18,7 +18,7 @@ import { Uniwind } from 'uniwind'import { useStore } from 'valtio-define'import { BreathingLight } from '@/components/breathing-light'import { Logo, Wordmark } from '@/components/icons'-import { WEBVIEW_LOAD_TIMEOUT_MS } from '@/config/constants'+import { SESSION_FORGET_TIMEOUT_MS, WEBVIEW_LOAD_TIMEOUT_MS } from '@/config/constants'import { useAppState } from '@/hooks/use-app-state'import { requestNotificationAccess, sendNativeNotification } from '@/hooks/use-notifications'import { connection } from '@/store/modules/connection'@@ -30,7 +30,12 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,const ref = useRef<WebView>(null)const { t } = useTranslation()const [nonce] = useState(randomUUID)- const mainUrlRef = useRef(buildConnectUrl(address))+ const [source] = useState(() => ({+ uri: !address.token && !connection.tokens[address.id] && !connection.history.some(entry => entry.id === address.id)+ ? new URL('/?pair=1', address.id).toString()+ : buildConnectUrl(address),+ }))+ const mainUrlRef = useRef(source.uri)const canGoBackRef = useRef(false)const focusRequestRef = useRef<{ requestId: string, focus: NotificationFocus } | null>(null)const documentReadyRef = useRef(false)@@ -85,6 +90,17 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,const timeout = setTimeout(setLoadingTimedOut, WEBVIEW_LOAD_TIMEOUT_MS, true)return () => clearTimeout(timeout)}, [documentGeneration, documentReady, state.loadError])+ // keep:effect Bound cookie clearing to this WebView's lifetime before removing its connection.+ useEffect(() => {+ if (state.forgettingOrigin !== address.id)+ return+ ref.current?.injectJavaScript(nativeMessageScript(address.id, nonce, { type: 'dsh://forget-session' }))+ const timeout = setTimeout(() => {+ if (generation === connection.viewGeneration && connection.forgettingOrigin === address.id)+ connection.remove(address.id)+ }, SESSION_FORGET_TIMEOUT_MS)+ return () => clearTimeout(timeout)+ }, [address.id, generation, nonce, state.forgettingOrigin])// keep:effect Route Android back to WebView history without consuming an open drawer's back event.useEffect(() => {const subscription = BackHandler.addEventListener('hardwareBackPress', () => {@@ -121,6 +137,13 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,const message = parseNativeMessage(nativeEvent.data, nativeEvent.url, address.id, nonce)if (!message || generation !== connection.viewGeneration)return+ if (message.type === 'dsh://session-forgotten') {+ if (connection.forgettingOrigin === address.id)+ connection.remove(address.id)+ return+ }+ if (connection.forgettingOrigin === address.id)+ returnif (message.type === 'dsh://bridge-ready') {if (connection.loadError)return@@ -132,6 +155,10 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,}if (!documentReadyRef.current || connection.loadError)return+ if (message.type === 'dsh://device-session') {+ connection.rememberDeviceSession(address.id, message.token, generation)+ return+ }if (message.type === 'dsh://theme-state') {Uniwind.setTheme(message.theme)return@@ -177,7 +204,7 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,<View className="flex-1"><WebViewref={ref}- source={{ uri: buildConnectUrl(address) }}+ source={source}style={{ flex: 1, backgroundColor: background }}injectedJavaScriptBeforeContentLoaded={shim}injectedJavaScript={shim}diff --git a/src-native/utils/bridge-protocol.test.ts b/src-native/utils/bridge-protocol.test.tsindex b32ddec7..6b5fc09f 100644--- a/src-native/utils/bridge-protocol.test.ts+++ b/src-native/utils/bridge-protocol.test.ts@@ -105,6 +105,14 @@ describe('connect URL and label', () => {expect(address.url).toBe('https://bridge.local:8443/workspaces/w-1?theme=dark&auth=old')})+ it('exchanges a device ticket only at its origin root without forwarding the deep route or public query', () => {+ const token = `v1.1700000000000.0.${'a'.repeat(64)}`+ const address = { id: 'https://bridge.local:8443', url: 'https://bridge.local:8443/tasks?session=7', host: 'bridge.local', port: 8443, token }+ expect(buildConnectUrl(address)).toBe(`https://bridge.local:8443/?auth=${token}`)+ expect(address.url).toBe('https://bridge.local:8443/tasks?session=7')+ expect(address.token).toBe(token)+ })+it('keeps a token-free URL unchanged', () => {expect(buildConnectUrl({ id: 'http://bridge.local', url: 'http://bridge.local/tasks?session=7', host: 'bridge.local', port: 80 })).toBe('http://bridge.local/tasks?session=7')})diff --git a/src-native/utils/bridge-protocol.ts b/src-native/utils/bridge-protocol.tsindex b9b93016..8b0b06e4 100644--- a/src-native/utils/bridge-protocol.ts+++ b/src-native/utils/bridge-protocol.ts@@ -66,8 +66,13 @@ export function parseQrPayload(raw: string): BridgeAddress | null {}}+export function isDeviceSession(value: unknown): value is string {+ return typeof value === 'string' && /^v1\.(?:0|[1-9]\d{0,15})\.0\.[a-f0-9]{64}$/u.test(value)+ && Number.isSafeInteger(Number(value.split('.')[1]))+}+export function buildConnectUrl(address: BridgeAddress): string {- const url = new URL(address.url)+ const url = isDeviceSession(address.token) ? new URL('/', address.id) : new URL(address.url)if (address.token)url.searchParams.set('auth', address.token)return url.toString()diff --git a/src-native/utils/webview-bridge.test.ts b/src-native/utils/webview-bridge.test.tsindex 45990b01..f89a07ef 100644--- a/src-native/utils/webview-bridge.test.ts+++ b/src-native/utils/webview-bridge.test.ts@@ -138,7 +138,8 @@ function createBrowser(options: { locationOrigin?: string, topFrame?: boolean, hdispatchEvent: vi.fn((event: Event) => documentEvents.dispatchEvent(event)),}const location = { origin: options.locationOrigin ?? origin }- const context = createVmContext({ window, document, location, MutationObserver: BrowserMutationObserver, Event, MessageEvent: BrowserMessageEvent, Date, setTimeout, clearTimeout })+ const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(new Response(null, { status: 404 }))+ const context = createVmContext({ window, document, location, fetch, MutationObserver: BrowserMutationObserver, Event, MessageEvent: BrowserMessageEvent, Date, setTimeout, clearTimeout })function run(script: string): unknown {return runInContext(script, context, { timeout: 1000 })}@@ -152,7 +153,7 @@ function createBrowser(options: { locationOrigin?: string, topFrame?: boolean, hfunction postMessage(data: unknown, eventOrigin = origin, source: unknown = window) {window.dispatchEvent(new BrowserMessageEvent('message', { data, origin: eventOrigin, source }))}- return { window, document, documentElement, body, styles, appendChild, mutations, location, posts, run, inject, postMessage }+ return { window, document, documentElement, body, styles, appendChild, mutations, location, posts, fetch, run, inject, postMessage }}function sessionNode(attributes: Record<string, string>): SessionNode {@@ -270,6 +271,67 @@ describe('parseNativeMessage', () => {})})+describe('paired device authorization bridge', () => {+ const token = `v1.1700000000000.0.${'a'.repeat(64)}`++ it('accepts a device ticket only through the nonce- and origin-verified native envelope', () => {+ const payload = { type: 'dsh://device-session', token }+ expect(parseNativeMessage(envelope(payload), nativeUrl, origin, nonce)).toEqual(payload)+ expect(parseNativeMessage(envelope(payload), nativeUrl, origin, 'stale')).toBeNull()+ expect(parseNativeMessage(envelope(payload), 'https://foreign.test/', origin, nonce)).toBeNull()+ for (const token of ['AB23CD45', '', `v1.1700000000000.1702592000000.${'a'.repeat(64)}`, `v1.9007199254740992.0.${'a'.repeat(64)}`, null, 123])+ expect(parseNativeMessage(envelope({ type: 'dsh://device-session', token }), nativeUrl, origin, nonce)).toBeNull()+ })++ it('fetches authorization once from a completed DSH app using its WebView cookies, including after manual pairing', async () => {+ const browser = createBrowser({ login: true })+ browser.fetch.mockResolvedValue(Response.json({ token }))+ browser.inject()+ expect(browser.fetch).not.toHaveBeenCalled()+ browser.window.__DSH_BOOT__ = {}+ browser.inject()+ await vi.waitFor(() => expect(browser.posts.mock.calls.some(([raw]) => parseNativeMessage(raw, nativeUrl, origin, nonce)?.type === 'dsh://device-session')).toBe(true))+ expect(browser.fetch).toHaveBeenCalledExactlyOnceWith(`${origin}/api/tauri/remote/access/session`, { credentials: 'same-origin', cache: 'no-store', redirect: 'error' })+ browser.inject()+ expect(browser.fetch).toHaveBeenCalledTimes(1)+ browser.window.dispatchEvent(new Event('pagehide'))+ })++ it.each([401, 404])('does not treat unsupported or unauthenticated session endpoint %s as a connection error', async (status) => {+ const browser = createBrowser()+ browser.fetch.mockResolvedValue(new Response(null, { status }))+ browser.window.__DSH_BOOT__ = {}+ browser.inject()+ await vi.waitFor(() => expect(browser.fetch).toHaveBeenCalledTimes(1))+ browser.inject()+ expect(browser.posts.mock.calls.map(([raw]) => parseNativeMessage(raw, nativeUrl, origin, nonce)?.type)).toEqual(['dsh://bridge-ready', 'dsh://theme-state'])+ browser.window.dispatchEvent(new Event('pagehide'))+ })++ it('ignores a credential response after navigation, nonce replacement or an explicit forget request', async () => {+ for (const boundary of ['navigation', 'nonce', 'forget']) {+ const browser = createBrowser()+ const pending = Promise.withResolvers<Response>()+ browser.fetch.mockReturnValueOnce(pending.promise).mockResolvedValue(new Response(null, { status: 204 }))+ browser.window.__DSH_BOOT__ = {}+ browser.inject()+ expect(browser.fetch).toHaveBeenCalledTimes(1)+ if (boundary === 'navigation')+ browser.window.dispatchEvent(new Event('pagehide'))+ else if (boundary === 'nonce')+ browser.window.__dshBridgeNonce = 'new-nonce'+ else+ browser.run(nativeMessageScript(origin, nonce, { type: 'dsh://forget-session' }))+ pending.resolve(Response.json({ token }))+ await vi.waitFor(() => expect(browser.fetch).toHaveBeenCalledTimes(boundary === 'forget' ? 2 : 1))+ await Promise.resolve()+ await Promise.resolve()+ expect(browser.posts.mock.calls.some(([raw]) => JSON.parse(raw).payload.type === 'dsh://device-session')).toBe(false)+ browser.window.dispatchEvent(new Event('pagehide'))+ }+ })+})+describe('trusted WebView theme and touch styling', () => {it.each(['light', 'dark', 'system'] as const)('accepts only the canonical theme source %s through authenticated IPC', (theme) => {expect(parseNativeMessage(envelope({ type: 'dsh://theme-state', theme }), nativeUrl, origin, nonce)).toEqual({ type: 'dsh://theme-state', theme })diff --git a/src-native/utils/webview-bridge.ts b/src-native/utils/webview-bridge.tsindex 648350d4..262db426 100644--- a/src-native/utils/webview-bridge.ts+++ b/src-native/utils/webview-bridge.ts@@ -1,11 +1,13 @@import type { Edge } from 'react-native-safe-area-context'import type { NativeNotificationMessage } from './notification-policy'import { FOCUS_RETRY_INTERVAL_MS, FOCUS_TIMEOUT_MS } from '@/config/constants'-import { isRecord, isTrustedOrigin } from './bridge-protocol'+import { isDeviceSession, isRecord, isTrustedOrigin } from './bridge-protocol'export type NativeWebViewMessage= | NativeNotificationMessage| { type: 'dsh://bridge-ready' }+ | { type: 'dsh://device-session', token: string }+ | { type: 'dsh://session-forgotten' }| { type: 'dsh://theme-state', theme: 'light' | 'dark' | 'system' }| { type: 'dsh://focus-result', requestId: string, handled: boolean }@@ -19,8 +21,10 @@ export function parseNativeMessage(raw: string, nativeUrl: string, expectedOrigiconst payload = value.payloadif (!isRecord(payload))return null- if (payload.type === 'dsh://bridge-ready')- return { type: 'dsh://bridge-ready' }+ if (payload.type === 'dsh://bridge-ready' || payload.type === 'dsh://session-forgotten')+ return { type: payload.type }+ if (payload.type === 'dsh://device-session')+ return isDeviceSession(payload.token) ? { type: 'dsh://device-session', token: payload.token } : nullif (payload.type === 'dsh://theme-state') {if (payload.theme !== 'light' && payload.theme !== 'dark' && payload.theme !== 'system')return null@@ -100,6 +104,9 @@ export function createNotificationShim(origin: string, nonce: string, nativeSafevar focusStartedAt = 0;var focusTimer = null;var results = new Map();+ var sessionRequested = false;+ var sessionForgotten = false;+ var sessionUrl = expectedOrigin + '/api/tauri/remote/access/session';function send(payload) {if (!active || window.__dshBridgeNonce !== nonce || !window.ReactNativeWebView) return false;var raw = JSON.stringify({ channel: 'dsh-bridge', origin: expectedOrigin, nonce: nonce, payload: payload });@@ -217,6 +224,13 @@ export function createNotificationShim(origin: string, nonce: string, nativeSafe}window.__dshBridgeReceive = function (data) {if (!active || window.__dshBridgeNonce !== nonce || !data || data.nonce !== nonce) return;+ if (data.type === 'dsh://forget-session') {+ if (sessionForgotten) return;+ sessionForgotten = true;+ if (typeof fetch === 'function') fetch(sessionUrl, { method: 'DELETE', credentials: 'same-origin', cache: 'no-store', redirect: 'error' })+ .then(function (response) { if (response.ok) send({ type: 'dsh://session-forgotten' }); }).catch(function () {});+ return;+ }if (data.type === 'dsh://visibility-state') {if (hidden !== !!data.hidden) {hidden = !!data.hidden;@@ -340,6 +354,15 @@ export function createNotificationShim(origin: string, nonce: string, nativeSafewindow.__dshBridgeThemeObserver = themeObserver;}syncTheme();+ if (readySent && !sessionRequested && !sessionForgotten && (window.__DSH_BOOT__ || window.__dshClientCtx) && typeof fetch === 'function') {+ sessionRequested = true;+ fetch(sessionUrl, { credentials: 'same-origin', cache: 'no-store', redirect: 'error' })+ .then(function (response) { return response.ok ? response.json() : null; })+ .then(function (data) {+ if (!sessionForgotten && location.origin === expectedOrigin && data && typeof data.token === 'string' && data.token.length <= 128)+ send({ type: 'dsh://device-session', token: data.token });+ }).catch(function () {});+ }clearTimeout(sessionWatchTimer);watchSessions();}diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 43cb1920..bbc190fe 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -1040,7 +1040,7 @@ dependencies = [[[package]]name = "deepseek-harness-desktop"-version = "0.24.0-beta.1"+version = "0.24.0-beta.2"dependencies = ["arboard","async-trait",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 85ab483c..b9da24f1 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "deepseek-harness-desktop"-version = "0.24.0-beta.1"+version = "0.24.0-beta.2"description = "Desktop application for DeepSeek Harness (dsh)"authors = [ "deepseek-harness-desktop contributors" ]edition = "2021"diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex d4be1124..a69c928e 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "DSH Tauri",- "version": "0.24.0-beta.1",+ "version": "0.24.0-beta.2","identifier": "dsh-tauri","build": {"beforeDevCommand": "pnpm dev",diff --git a/test/mobile-release-workflows.test.ts b/test/mobile-release-workflows.test.tsindex c2184a6b..50dad68d 100644--- a/test/mobile-release-workflows.test.ts+++ b/test/mobile-release-workflows.test.ts@@ -145,7 +145,7 @@ describe('mobile release workflow contracts', () => {it('pins TestFlight to the locally verified Xcode toolchain on macOS 26', () => {const signed = readSource('.github/workflows/release-testflight.yml')expect(signed).toContain('runs-on: macos-26')- expect(signed).toContain('xcode-version: \'26.4.1\'')+ expect(signed).toContain('xcode-version: 26.4.1')expect(signed).not.toContain('runs-on: macos-15-intel')})