DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(ssh): 隧道自注会话 Cookie——iframe 第三方上下文彻底免 401
Menghuan19185a01b0509c65
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts b/packages/dsh-tauri-ssh/src/host/service/transport.test.tsindex 7c4c9171..95876d51 100644--- a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts@@ -6,7 +6,7 @@ import { Server, connect as tcpConnect } from 'node:net'import { PassThrough } from 'node:stream'import { describe, expect, it, vi } from 'vitest'import { MachineId } from '../types/index'-import { classifyConnectFailure, describeConnectFailure, loginShell, shQuote, Ssh2Transport } from './transport'+import { classifyConnectFailure, describeConnectFailure, injectCookieHead, loginShell, shQuote, Ssh2Transport } from './transport'const profile: MachineProfile = {id: MachineId('m1'),@@ -811,3 +811,63 @@ describe('ssh2Transport ProxyJump', () => {expect(jump?.ended).toBe(true)})})++describe('injectCookieHead', () => {+ it('replaces Cookie, forces Connection: close, keeps the request line first', () => {+ const head = 'GET / HTTP/1.1\r\nHost: 127.0.0.1:5000\r\nConnection: keep-alive\r\nCookie: stale=1'+ const out = injectCookieHead(head, 'dsh-auth-x=v1.signed')+ const lines = out.split('\r\n')+ expect(lines[0]).toBe('GET / HTTP/1.1')+ expect(lines).toContain('Cookie: dsh-auth-x=v1.signed')+ expect(lines).toContain('Connection: close')+ expect(lines.some(line => /keep-alive/iu.test(line))).toBe(false)+ expect(lines.filter(line => /^cookie:/iu.test(line))).toHaveLength(1)+ })++ it('keeps Connection: Upgrade untouched for websocket handshakes', () => {+ const head = 'GET /ws HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: websocket'+ const out = injectCookieHead(head, 'dsh-auth-x=v1.signed')+ expect(out).toContain('Connection: Upgrade')+ expect(out).not.toContain('Connection: close')+ expect(out).toContain('Cookie: dsh-auth-x=v1.signed')+ })+})++describe('tunnel cookie injection', () => {+ it('stamps the request head with the minted cookie through the pipe', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const injection = { cookie: 'dsh-auth-x=v1.signed' as string | undefined }+ const tunnel = await session.openTunnel(3080, undefined, injection)+ const socket = tcpConnect(tunnel.localPort, '127.0.0.1')+ await new Promise<void>(resolve => socket.once('connect', () => resolve()))+ // PassThrough 回环:写入 channel 的字节流(= 注入后的请求)回到 socket+ const echoed: Buffer[] = []+ socket.on('data', chunk => echoed.push(chunk as Buffer))+ socket.write('GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n')+ await new Promise(resolve => setTimeout(resolve, 30))+ const received = Buffer.concat(echoed).toString('latin1')+ expect(received).toContain('Cookie: dsh-auth-x=v1.signed')+ expect(received).toContain('Connection: close')+ expect(received.startsWith('GET / HTTP/1.1')).toBe(true)+ socket.destroy()+ await tunnel.close()+ await session.close()+ })++ it('without a minted cookie the tunnel stays a plain pipe', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const tunnel = await session.openTunnel(3080)+ const socket = tcpConnect(tunnel.localPort, '127.0.0.1')+ await new Promise<void>(resolve => socket.once('connect', () => resolve()))+ const echoed: Buffer[] = []+ socket.on('data', chunk => echoed.push(chunk as Buffer))+ socket.write('ping')+ await new Promise(resolve => setTimeout(resolve, 30))+ expect(Buffer.concat(echoed).toString('latin1')).toBe('ping')+ socket.destroy()+ await tunnel.close()+ await session.close()+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-ssh/src/host/service/transport.tsindex 3ecd6a7b..03737ce1 100644--- a/packages/dsh-tauri-ssh/src/host/service/transport.ts+++ b/packages/dsh-tauri-ssh/src/host/service/transport.ts@@ -5,12 +5,13 @@* @module dsh-tauri-ssh/host/service/transport*/-import type { Buffer } from 'node:buffer'+import { Buffer } from 'node:buffer'import type { AddressInfo, Server } from 'node:net'import type { Duplex } from 'node:stream'import type { ConnectConfig } from 'ssh2'import type { MachineProfile, SshAuthMethod } from '../types/index'import type { ResolvedSshAuth } from './ssh-config'+import { get as httpGet } from 'node:http'import { createServer } from 'node:net'import process from 'node:process'import { Client } from 'ssh2'@@ -43,6 +44,21 @@ export interface SshExecOptions {stdinData?: Buffer}+/**+ * Cookie-injection slot of one tunnel. The remote `dsh web` session cookie is+ * `SameSite=Strict`: an iframe embedding the tunnel URL is a cross-site+ * context and neither stores nor sends it (the shell's remote view showed+ * the bare 401 page even with the launch token in the URL). With a cookie+ * minted at connect time (one local `GET …/?token=…` round-trip, no redirect+ * follow), the tunnel stamps every request head itself — any embedding+ * context (iframe, webview, browser tab) is authenticated transparently.+ * `cookie === undefined` keeps the plain TCP pipe.+ */+export interface TunnelHeaderInjection {+ /** The raw `Cookie` header value (`name=value`); read per accepted connection. */+ cookie: string | undefined+}+/** A local loopback listener forwarding into the SSH tunnel. */export interface SshTunnelHandle {/** The bound loopback port (0 = ephemeral, read from the server). */@@ -72,9 +88,12 @@ export interface SshSession {* @param preferredLocalPort - keep the tunnel's published URL stable across* reconnects by re-binding this port when possible (falls back to an* ephemeral port when it is taken).+ * @param injection - mutable cookie-injection slot; when `cookie` is set,+ * every request head through the tunnel gets it stamped (see+ * {@link TunnelHeaderInjection}).* @returns the local listener handle.*/- openTunnel: (remotePort: number, preferredLocalPort?: number) => Promise<SshTunnelHandle>+ openTunnel: (remotePort: number, preferredLocalPort?: number, injection?: TunnelHeaderInjection) => Promise<SshTunnelHandle>/*** Register the session-closed callback (connection dropped, server went* away, or {@link close} ran).@@ -407,7 +426,7 @@ export class Ssh2Transport implements SshTransport {}}client.connect({- ...sock === undefined ? {} : { sock: sock as ConnectConfig['sock'] },+ ...sock === undefined ? {} : { sock: sock as NonNullable<ConnectConfig['sock']> },host: auth.host,port: auth.port,username: auth.username,@@ -546,8 +565,8 @@ class Ssh2Session implements SshSession {})}- openTunnel(remotePort: number, preferredLocalPort?: number): Promise<SshTunnelHandle> {- return this.listenTunnel(remotePort, preferredLocalPort, true)+ openTunnel(remotePort: number, preferredLocalPort?: number, injection?: TunnelHeaderInjection): Promise<SshTunnelHandle> {+ return this.listenTunnel(remotePort, preferredLocalPort, true, injection)}/**@@ -555,7 +574,7 @@ class Ssh2Session implements SshSession {* reconnect can re-publish the same tunnel URL; a taken port falls back* to an ephemeral one (only the first, deliberate preference retries).*/- private listenTunnel(remotePort: number, preferredLocalPort: number | undefined, allowFallback: boolean): Promise<SshTunnelHandle> {+ private listenTunnel(remotePort: number, preferredLocalPort: number | undefined, allowFallback: boolean, injection?: TunnelHeaderInjection): Promise<SshTunnelHandle> {return new Promise<SshTunnelHandle>((resolve, reject) => {const sockets = new Set<import('node:net').Socket>()const server: Server = createServer((socket) => {@@ -574,7 +593,12 @@ class Ssh2Session implements SshSession {return}channel.on('error', () => socket.destroy())- socket.pipe(channel).pipe(socket)+ const cookie = injection?.cookie+ if (cookie === undefined) {+ socket.pipe(channel).pipe(socket)+ return+ }+ pipeChannelWithCookie(socket, channel, cookie)})})server.on('error', (error: NodeJS.ErrnoException) => {@@ -582,7 +606,7 @@ class Ssh2Session implements SshSession {// The preferred port was reclaimed while we were away; an// ephemeral port keeps the reconnect alive (the URL change rides// the status publication).- void this.listenTunnel(remotePort, undefined, false).then(resolve, reject)+ void this.listenTunnel(remotePort, undefined, false, injection).then(resolve, reject)return}reject(error)@@ -615,6 +639,89 @@ class Ssh2Session implements SshSession {}}+/** Request-head cap for the cookie injector; a head never completing within it pipes raw (fail-open). */+const TUNNEL_HEAD_CAP = 64 * 1024++/**+ * Stamp one request head with the minted cookie: any existing `Cookie` line+ * is replaced (the browser has none worth keeping in an iframe context) and+ * `Connection` collapses to `close` — one request per connection means the+ * injector only ever parses the FIRST head. Upgrade (websocket) handshakes+ * keep their `Connection: Upgrade` untouched; after the head the stream+ * pipes raw in both directions.+ */+export function injectCookieHead(head: string, cookie: string): string {+ const lines = head.split('\r\n')+ const isUpgrade = lines.some(line => /^connection:\s*upgrade/iu.test(line))+ const kept = lines.filter(line =>+ !/^cookie:/iu.test(line) && (isUpgrade || !/^connection:/iu.test(line)))+ // The request line stays first; the injected headers follow it.+ kept.splice(1, 0, `Cookie: ${cookie}`)+ if (!isUpgrade)+ kept.splice(2, 0, 'Connection: close')+ return kept.join('\r\n')+}++/** Pipe one tunneled connection, stamping the first request head with the cookie. */+function pipeChannelWithCookie(+ socket: import('node:net').Socket,+ channel: Duplex,+ cookie: string,+): void {+ const buffered: Buffer[] = []+ let bufferedLength = 0+ let injected = false+ socket.on('data', (chunk: Buffer) => {+ if (injected) {+ channel.write(chunk)+ return+ }+ buffered.push(chunk)+ bufferedLength += chunk.length+ const whole = Buffer.concat(buffered)+ const headEnd = whole.indexOf('\r\n\r\n')+ if (headEnd === -1) {+ if (bufferedLength > TUNNEL_HEAD_CAP) {+ injected = true+ channel.write(whole)+ }+ return+ }+ injected = true+ const head = whole.subarray(0, headEnd).toString('latin1')+ const rest = whole.subarray(headEnd)+ channel.write(Buffer.concat([Buffer.from(injectCookieHead(head, cookie), 'latin1'), rest]))+ })+ socket.on('end', () => channel.end())+ channel.on('end', () => socket.end())+ channel.pipe(socket)+}++/**+ * Mint the tunnel's session cookie: GET the authenticated URL once WITHOUT+ * following the 303 and read the `name=value` pair back from `set-cookie`.+ * Resolves `undefined` on any failure (no token endpoint, timeout, transport+ * error) — the tunnel then stays a plain pipe and the `?token=` URL remains+ * the top-level fallback. The 3 s cap keeps a black-hole remote from+ * stalling the connect; the request itself needs no cookie (the query token+ * is the credential).+ */+export function mintTunnelCookie(authenticatedUrl: string): Promise<string | undefined> {+ return new Promise((resolve) => {+ const request = httpGet(authenticatedUrl, (response) => {+ response.resume()+ const raw = response.headers['set-cookie']?.[0]+ const pair = raw === undefined ? undefined : raw.split(';')[0]?.trim()+ resolve(pair === undefined || pair === '' ? undefined : pair)+ })+ request.on('error', () => resolve(undefined))+ request.setTimeout(3_000, () => {+ request.destroy()+ resolve(undefined)+ })+ })+}+/** Mirror fetch's abort rejection: the signal's reason when present, else a DOMException-style AbortError. */function abortError(signal: AbortSignal): Error {const reason: unknown = signal.reason