Prechádzať zdrojové kódy

fix(connection): fence every /api request behind one browser-trust check

The only browser-trust guard covered host.pickDirectory, while the
consequential methods (session.prompt drives bash) accepted any Host —
open to DNS rebinding, where a rebound page reads and writes the API as
if same-origin and only the Host header betrays the attacker's domain.

The pickDirectory-specific loopback guard becomes a prefix-wide fence:
Host must be loopback or an exact host[:port] from the new trustedHosts
config, an attached Origin must equal that authority, and explicit
cross-site markers are refused; requests without browser markers (curl,
tests, native clients) pass, because without a browser there is no
confused deputy. The loopback-socket check is dropped — binding policy
expresses reachability, and the fence is not an auth layer. The Agent
Note records the full threat model and the alternatives.
creatixchu 1 mesiac pred
rodič
commit
01d68dee4e

+ 6 - 0
.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md
+2026-07-28-api-browser-trust-boundary.md: c620f1a65e3890bbd2580415e55b25436fefe36e
+2026-07-28-api-browser-trust-boundary.zh.md: 0452eff1017b2f70a00e67c5cfce8dba3a840539

+ 31 - 0
.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md

@@ -0,0 +1,31 @@
+# Agent Note: One carrier-level browser-trust boundary for the whole /api surface
+
+Status: implemented
+
+English | [中文](2026-07-28-api-browser-trust-boundary.zh.md)
+
+## Problem
+
+The web GUI host serves `/api` over plain HTTP (default `127.0.0.1:3080`, `--host 0.0.0.0` supported), and the surface includes remote-code-execution-grade methods — `session.prompt` drives an agent that runs bash. A browser turns the operator into a confused deputy against such a local API in two classic ways: a malicious page fires a "simple" cross-site POST (`text/plain` — sent without a CORS preflight) whose side effects execute even though the response stays unreadable, and a DNS-rebound origin talks to the socket as if same-origin, making CORS inapplicable entirely, with only the `Host` header betraying the attacker's domain. Before this decision the system's only browser-trust check (`isTrustedNativeDialogRequest`: loopback socket + same-origin + loopback Host) guarded exactly one cosmetic route — `host.pickDirectory`, whose native dialog pops on the host's screen — while every consequential method was unguarded. Guarding per-RPC also could not survive the upcoming in-app directory browser, whose whole point is serving legitimately remote clients that a loopback rule would refuse.
+
+## Decision
+
+Enforce browser trust once, at the carrier, for the entire `/api` prefix — two halves in two stacked PRs:
+
+- **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers.
+- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: `Host` must be loopback or an exact `host[:port]` from the plugin's `trustedHosts` config (rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. Requests without browser markers pass — a non-browser client is the principal itself, not a deputy. `host.pickDirectory` loses its bespoke guard and rides the same fence.
+
+Two boundaries stay deliberately out of scope: reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and authentication for genuinely remote deployments is deferred work recorded in the connection README — the fence is a confused-deputy defense, not an auth layer. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming remote authorities, the socket address adds nothing a header fence does not already cover.
+
+## Alternatives considered
+
+- **Per-RPC guards (status quo extended).** Rejected: the guard list trails the method list forever, the highest-value methods were already unguarded, and a loopback rule on browse RPCs would break the remote deployments they exist for.
+- **CORS headers + credential omission.** Rejected: we never want cross-origin reads at all, so answering preflights only widens the surface; refusing them is strictly stronger and simpler.
+- **Auth tokens now.** Rejected for this change: token minting/storage/rotation is real product surface; the fence closes the browser-deputy holes today without pre-deciding the auth design.
+
+## Consequences
+
+- Any future `/api` method is covered by construction; there is no per-route trust decision left to forget.
+- Non-loopback deployments must declare their serving authorities in `trustedHosts` or browsers are refused; plain curl-shape automation is unaffected either way.
+- Clients must label POST bodies `application/json` (ours always did; raw-fetch tests gained the header).
+- The trusted-network assumption of an unauthenticated `0.0.0.0` deployment is now documented instead of implicit.

+ 31 - 0
.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md

@@ -0,0 +1,31 @@
+# Agent Note:整个 /api 面共用一道载体级浏览器信任边界
+
+状态:已实现
+
+[English](2026-07-28-api-browser-trust-boundary.md) | 中文
+
+## 问题
+
+Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--host 0.0.0.0`),而这个面上有远程代码执行级别的方法——`session.prompt` 驱动的 agent 可以运行 bash。浏览器会用两种经典方式把操作者变成攻击此类本地 API 的"混淆代理人":恶意页面发出跨站"简单请求" POST(`text/plain`——不经 CORS 预检即发出),其副作用照常执行、只是响应不可读;以及 DNS rebinding 后的源以"同源"身份直连 socket,CORS 整体失效,只有 `Host` 头会暴露攻击者的域名。在本决策之前,系统里唯一的浏览器信任检查(`isTrustedNativeDialogRequest`:回环 socket + 同源 + 回环 Host)只守着一个装饰性的路由——`host.pickDirectory`,其原生对话框弹在宿主屏幕上——而所有真正要命的方法都在裸奔。按 RPC 逐个设防也活不过即将到来的应用内目录浏览器:它存在的意义就是服务合法的远程客户端,回环规则恰恰会拒绝它们。
+
+## 决策
+
+在载体层对整个 `/api` 前缀一次性执行浏览器信任检查——两半各占一个栈式 PR:
+
+- **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站"简单请求"由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。
+- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:`Host` 必须是回环地址,或与插件 `trustedHosts` 配置中的某个 `host[:port]` 精确匹配(rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不带浏览器标头的请求放行——非浏览器客户端是委托人本人,不是代理人。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。
+
+两条边界刻意留在范围之外:可达性归 webserver 绑定配置(`host: 127.0.0.1 | 0.0.0.0`)管辖;真正远程部署的认证是延期工作,记录在 connection README——这道栅栏是混淆代理人防御,不是认证层。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名远程权威之后,socket 地址提供不了头部栅栏覆盖不到的任何东西。
+
+## 曾考虑的替代方案
+
+- **按 RPC 设防(延续现状)。** 否决:守卫清单永远追着方法清单跑,价值最高的方法本来就没被守住,而 browse RPC 上的回环规则会破坏它们为之存在的远程部署。
+- **CORS 头 + 省略凭据。** 否决:我们根本不想要任何跨源读取,应答预检只会扩大暴露面;拒绝预检严格更强也更简单。
+- **现在就上认证令牌。** 在本变更中否决:令牌的签发/存储/轮换是真实的产品面;栅栏今天就能封死浏览器代理人漏洞,无需预先决定认证设计。
+
+## 后果
+
+- 未来任何 `/api` 方法天然在覆盖范围内;不存在会被遗忘的按路由信任决定。
+- 非回环部署必须在 `trustedHosts` 中声明服务权威,否则浏览器会被拒绝;curl 形态的自动化不受影响。
+- 客户端必须给 POST 体标注 `application/json`(我们自己的客户端一向如此;裸 fetch 测试补上了该头)。
+- 无认证 `0.0.0.0` 部署的"信任网络"假设从隐含变为成文。

+ 19 - 1
docs/config-catalog.md

@@ -270,6 +270,25 @@ Depends on: [`agentCore`](../packages/examples/agent-spine-demo/src/index.ts) ·
 
 Source: [`packages/examples/cli-demo/src/index.ts:26`](../packages/examples/cli-demo/src/index.ts)
 
+## `@deepseek-ai/dsh-client-connection`
+
+Requires: `httpServer` · `apiProxy`
+
+```ts config-catalog
+/** Plugin config: the deployment's non-loopback serving authorities. */
+export interface ConnectionConfig {
+  /**
+   * Exact `host[:port]` authorities this deployment serves beyond loopback.
+   * The /api trust fence refuses any request whose Host is neither loopback
+   * nor listed here, so a non-loopback (`0.0.0.0`) deployment must declare
+   * the names it is reached by.
+   */
+  trustedHosts?: string[]
+}
+```
+
+Source: [`packages/client/connection/src/index.ts:20`](../packages/client/connection/src/index.ts)
+
 ## `@deepseek-ai/dsh-client-hmr`
 
 Requires: `clientModuleHost` · `httpServer`
@@ -2143,7 +2162,6 @@ Source: [`packages/context/workspace-context/src/config.ts:17`](../packages/cont
 These load from a `cordis.yml` entry with no `config:` block; they declare no config surface.
 
 - `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts))
-- `@deepseek-ai/dsh-client-connection` — requires `httpServer` · `apiProxy` ([`packages/client/connection/src/index.ts`](../packages/client/connection/src/index.ts))
 - `@deepseek-ai/dsh-client-locale` ([`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts))
 - `@deepseek-ai/dsh-client-modules` — requires `httpServer` · `loader` ([`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts))
 - `@deepseek-ai/dsh-client-runtime` ([`packages/client/runtime/src/index.ts`](../packages/client/runtime/src/index.ts))

+ 3 - 3
packages/client/connection/README.i18n.yaml

@@ -1,6 +1,6 @@
 # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
-#   pnpm run verify-translation-pairing --write
-README.md: 80228a180faba0c556ff720e999b29b5bb1635b6
-README.zh.md: f4b857886bfafa891ceb1bd6b79b27e1fb725819
+#   pnpm run verify-translation-pairing --write packages/client/connection/README.md
+README.md: a301b85d707d17d1e8159655b540556eee5c9d83
+README.zh.md: 88d7aa806167033308a9913053f621ecea07c3d8

+ 4 - 0
packages/client/connection/README.md

@@ -4,6 +4,10 @@ English | [中文](README.zh.md)
 
 Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared api client + single-consumer stream-loop starter); the export face carries the wire contract types, the `AbstractApiClient` seam, and the loop's sink/config types. The platform subclasses (WebApiClient/FixtureApiClient), the ConnectionController loop, and the fixture data source are package-internal — apply selects and drives them; tests reach them via src. Contract: api-contracts v3 §3.
 
+## /api browser-trust fence
+
+The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`): the `Host` header must be a loopback authority or an exact `host[:port]` entry from the plugin's `trustedHosts` config (DNS-rebinding defense), an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. Requests without browser markers (curl, tests, native clients) pass — without a browser there is no confused deputy. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment must therefore list the authorities it is reached by in `trustedHosts`; the fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md).
+
 ## Keyless fixture
 
 Any `fixture` query parameter selects the in-memory carrier. `fixture=empty` starts with no Workspace or Session; `fixturePrompt=reject` rejects prompts before acceptance; `fixtureAttach=fail` publishes a Session but rejects its Workspace attachment; `fixtureSessionCreate=drop-response` publishes and frames a Session before dropping the create response; and `fixtureFrames=workspace-first` reverses the default session-first create-frame order. Workspace creation by name/path and caller-preallocated SessionIds remain deterministic enough for assembled Web tests to reconcile list and frame arrival.

+ 4 - 0
packages/client/connection/README.zh.md

@@ -4,6 +4,10 @@
 
 协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 单消费方流循环启动器);导出表层携带协议契约类型、`AbstractApiClient` seam,以及循环的 sink/配置类型。平台子类(WebApiClient/FixtureApiClient)、ConnectionController 循环和 fixture 数据源都属于包内部:apply 负责选择并驱动它们,测试则通过 src 访问。契约:api-contracts v3 §3。
 
+## /api 浏览器信任栅栏
+
+node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`):`Host` 头必须是回环地址权威,或与插件 `trustedHosts` 配置中的某个 `host[:port]` 精确匹配(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不带浏览器标头的请求(curl、测试、原生客户端)直接放行——没有浏览器就不存在"混淆代理人"。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署必须在 `trustedHosts` 中列出自己被访问时使用的权威;这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。
+
 ## 无密钥 fixture
 
 任何 `fixture` 查询参数都会选择内存载体。`fixture=empty` 启动时不含 Workspace 或 Session;`fixturePrompt=reject` 在接受前拒绝提示词;`fixtureAttach=fail` 发布 Session 但拒绝将其附加到 Workspace;`fixtureSessionCreate=drop-response` 在丢弃创建响应前发布 Session 并为其发出帧;`fixtureFrames=workspace-first` 则反转默认的 Session 优先创建帧顺序。按名称/路径创建 Workspace 以及由调用方预先分配 SessionId,均具有足够的确定性,组装后的 Web 测试可以据此协调列表与帧的到达。

+ 2 - 1
packages/client/connection/package.json

@@ -32,7 +32,8 @@
     "@deepseek-ai/dsh-host-apiproxy": "workspace:^",
     "@deepseek-ai/dsh-llm": "workspace:^",
     "@deepseek-ai/dsh-session": "workspace:^",
-    "@deepseek-ai/dsh-tools": "workspace:^"
+    "@deepseek-ai/dsh-tools": "workspace:^",
+    "schemastery": "^3.18.0"
   },
   "files": [
     "lib/index.js",

+ 71 - 0
packages/client/connection/src/api-request-trust.ts

@@ -0,0 +1,71 @@
+/**
+ * Browser-trust fence for every /api request. Defends the two confused-deputy
+ * paths a browser opens against a local HTTP API — DNS rebinding (Host names
+ * the attacker's domain while the socket reaches this server) and cross-site
+ * requests fired from a malicious page — without blocking non-browser clients
+ * (no browser markers → no deputy to confuse) or legitimately remote browsers
+ * (their authority is declared via `trustedHosts`). Network reachability and
+ * authentication stay out of scope: binding policy belongs to the webserver
+ * config, and this fence is not an auth layer.
+ */
+
+import type { IncomingHttpHeaders } from 'node:http'
+
+/** The request facts the fence reads (structural subset of IncomingMessage). */
+interface ApiTrustRequest {
+  headers: IncomingHttpHeaders
+}
+
+function header(headers: IncomingHttpHeaders, name: string): string | undefined {
+  const value = headers[name]
+  return typeof value === 'string' ? value : undefined
+}
+
+function isLoopbackHostname(hostname: string): boolean {
+  if (hostname === 'localhost' || hostname === '[::1]') return true
+  const parts = hostname.split('.')
+  return parts.length === 4
+    && parts[0] === '127'
+    && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
+}
+
+/** Hostname of a Host-header authority (port stripped, lowercased, IPv6 bracketed), or undefined when unparsable. */
+function authorityHostname(authority: string): string | undefined {
+  try {
+    // http: is a WHATWG "special scheme": parsing yields a non-empty hostname or throws.
+    return new URL(`http://${authority}`).hostname
+  } catch {
+    return undefined
+  }
+}
+
+/**
+ * Decide whether one /api request may reach the RPC bridge.
+ * @param request - node HTTP request facts (headers).
+ * @param trustedHosts - exact non-loopback `host[:port]` authorities this deployment serves.
+ * @returns true when the Host is ours and any browser markers are same-origin.
+ */
+export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: readonly string[]): boolean {
+  // Host fence (DNS-rebinding defense): the browser fills Host from the URL it
+  // believes it is talking to, so a rebound page carries the attacker's domain
+  // here even though the socket lands on this server.
+  const host = header(request.headers, 'host')
+  if (host === undefined) return false
+  const hostname = authorityHostname(host)
+  if (hostname === undefined) return false
+  if (!isLoopbackHostname(hostname) && !trustedHosts.includes(host)) return false
+  // Cross-site fence: modern browsers label the initiator relationship on
+  // every fetch; an explicit cross-site marker is refused regardless of Origin.
+  if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false
+  // Origin fence: when a browser attaches an Origin it must be exactly this
+  // authority. Absent Origin = non-browser client (curl, tests, native shells)
+  // — allowed, because without a browser there is no confused deputy. The
+  // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused.
+  const origin = header(request.headers, 'origin')
+  if (origin === undefined) return true
+  try {
+    return new URL(origin).host === host
+  } catch {
+    return false
+  }
+}

+ 25 - 6
packages/client/connection/src/index.ts

@@ -1,11 +1,12 @@
 /** Host HTTP bridge for browser-client RPC. */
 import type { Context } from 'cordis'
+import z from 'schemastery'
 // Activates the httpServer Context merge used below.
 import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
 import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
 import { API_PATH } from './api-path.ts'
 import { bridge } from './http-bridge.ts'
-import { isTrustedNativeDialogRequest } from './native-dialog-request.ts'
+import { isTrustedApiRequest } from './api-request-trust.ts'
 
 export { API_PATH } from './api-path.ts'
 
@@ -15,19 +16,37 @@ export const name = 'client-connection'
 /** Services required before mounting the route. */
 export const inject = ['httpServer', 'apiProxy']
 
+/** Plugin config: the deployment's non-loopback serving authorities. */
+export interface ConnectionConfig {
+  /**
+   * Exact `host[:port]` authorities this deployment serves beyond loopback.
+   * The /api trust fence refuses any request whose Host is neither loopback
+   * nor listed here, so a non-loopback (`0.0.0.0`) deployment must declare
+   * the names it is reached by.
+   */
+  trustedHosts?: string[]
+}
+
+export const Config: z<ConnectionConfig> = z.object({
+  trustedHosts: z.array(String).default([]),
+})
+
 /**
- * Mounts the API gateway under the browser transport prefix.
+ * Mounts the API gateway under the browser transport prefix. Every request on
+ * the prefix passes the browser-trust fence first (DNS-rebinding and
+ * cross-site defense — [api-request-trust](./api-request-trust.ts)).
  * @param ctx - Host plugin context.
+ * @param config - resolved plugin config (schema defaults applied).
  */
-export function apply(ctx: Context): void {
+export function apply(ctx: Context, config?: ConnectionConfig): void {
+  // The Loader resolves schema defaults; hand-built test contexts may pass none.
+  const trustedHosts = config?.trustedHosts ?? []
   const apiHandler = toFetchHandler(ctx.apiProxy)
   const route: WebRoute = {
     kind: 'prefix',
     path: API_PATH,
     handler: async (req, res) => {
-      const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
-      if (pathname === `${API_PATH}/host.pickDirectory`
-        && !isTrustedNativeDialogRequest(req)) {
+      if (!isTrustedApiRequest(req, trustedHosts)) {
         res.writeHead(403)
         res.end('forbidden')
         return

+ 0 - 52
packages/client/connection/src/native-dialog-request.ts

@@ -1,52 +0,0 @@
-/** Trust check for browser requests that can open an operating-system dialog. */
-
-import type { IncomingHttpHeaders } from 'node:http'
-
-interface NativeDialogRequest {
-  headers: IncomingHttpHeaders
-  socket: { remoteAddress?: string | undefined }
-}
-
-function header(headers: IncomingHttpHeaders, name: string): string | undefined {
-  const value = headers[name]
-  return typeof value === 'string' ? value : undefined
-}
-
-function isLoopback(address: string | undefined): boolean {
-  if (address === undefined) return false
-  if (address === '::1') return true
-  const ipv4 = address.startsWith('::ffff:') ? address.slice('::ffff:'.length) : address
-  const first = ipv4.split('.')[0]
-  return first === '127'
-}
-
-function isLoopbackHostname(hostname: string): boolean {
-  if (hostname === 'localhost' || hostname === '[::1]' || hostname === '::1') return true
-  const parts = hostname.split('.')
-  return parts.length === 4
-    && parts[0] === '127'
-    && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
-}
-
-/**
- * Require a local socket plus browser-controlled same-origin metadata.
- * @param request - the node HTTP request facts used by the carrier guard.
- * @returns true only for a same-origin browser request whose peer and URL are loopback.
- */
-export function isTrustedNativeDialogRequest(request: NativeDialogRequest): boolean {
-  if (!isLoopback(request.socket.remoteAddress)) return false
-  if (header(request.headers, 'sec-fetch-site') !== 'same-origin') return false
-  const origin = header(request.headers, 'origin')
-  const host = header(request.headers, 'host')
-  if (origin === undefined || host === undefined) return false
-  try {
-    const parsed = new URL(origin)
-    const hostUrl = new URL(`http://${host}`)
-    return (parsed.protocol === 'http:' || parsed.protocol === 'https:')
-      && parsed.host === host
-      && isLoopbackHostname(parsed.hostname)
-      && isLoopbackHostname(hostUrl.hostname)
-  } catch {
-    return false
-  }
-}

+ 60 - 0
packages/client/connection/tests/api-request-trust.spec.ts

@@ -0,0 +1,60 @@
+/** Behavior of the /api browser-trust fence (rebinding + cross-site defense). */
+
+import { describe, expect, it } from 'vitest'
+import { isTrustedApiRequest } from '../src/api-request-trust.ts'
+
+function request(headers: Record<string, string | undefined>): { headers: Record<string, string | undefined> } {
+  return { headers }
+}
+
+describe('isTrustedApiRequest', () => {
+  it('accepts loopback Hosts in every spelling, with and without ports', () => {
+    for (const host of ['localhost', 'localhost:3080', '127.0.0.1', '127.0.0.1:3080', '127.8.9.10:80', '[::1]', '[::1]:3080', 'LOCALHOST:3080']) {
+      expect(isTrustedApiRequest(request({ host }), [])).toBe(true)
+    }
+  })
+
+  it('accepts non-browser requests (no Origin, no sec-fetch-site) — curl, tests, native clients', () => {
+    expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080' }), [])).toBe(true)
+  })
+
+  it('refuses a rebound Host: the attacker domain names the socket it did not expect', () => {
+    expect(isTrustedApiRequest(request({
+      host: 'evil.example:3080',
+      origin: 'http://evil.example:3080',
+      'sec-fetch-site': 'same-origin',
+    }), [])).toBe(false)
+  })
+
+  it('accepts a declared public authority only on exact host[:port] match', () => {
+    const headers = { host: 'harness.internal:3080', origin: 'http://harness.internal:3080' }
+    expect(isTrustedApiRequest(request(headers), ['harness.internal:3080'])).toBe(true)
+    expect(isTrustedApiRequest(request(headers), ['harness.internal'])).toBe(false)
+    expect(isTrustedApiRequest(request(headers), [])).toBe(false)
+  })
+
+  it('refuses cross-origin browser markers even on a loopback Host', () => {
+    // Origin present and different → cross-site request that survived preflight rules.
+    expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', origin: 'http://evil.example' }), [])).toBe(false)
+    // Explicit cross-site label → refused regardless of Origin.
+    expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', 'sec-fetch-site': 'cross-site' }), [])).toBe(false)
+    // Opaque origin (sandboxed iframe, file: page) parses to no authority.
+    expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', origin: 'null' }), [])).toBe(false)
+  })
+
+  it('accepts a same-origin browser request', () => {
+    expect(isTrustedApiRequest(request({
+      host: 'localhost:3080',
+      origin: 'http://localhost:3080',
+      'sec-fetch-site': 'same-origin',
+    }), [])).toBe(true)
+  })
+
+  it('refuses malformed authorities', () => {
+    expect(isTrustedApiRequest(request({}), [])).toBe(false)
+    expect(isTrustedApiRequest(request({ host: '' }), [])).toBe(false)
+    expect(isTrustedApiRequest(request({ host: 'bad host' }), [])).toBe(false)
+    expect(isTrustedApiRequest(request({ host: '127.0.0.999' }), [])).toBe(false)
+    expect(isTrustedApiRequest(request({ host: '128.0.0.1' }), [])).toBe(false)
+  })
+})

+ 0 - 57
packages/client/connection/tests/native-dialog-request.spec.ts

@@ -1,57 +0,0 @@
-import type { IncomingHttpHeaders } from 'node:http'
-import { describe, expect, it } from 'vitest'
-import { isTrustedNativeDialogRequest } from '../src/native-dialog-request.ts'
-
-function request(
-  remoteAddress: string | undefined,
-  headers: IncomingHttpHeaders = {
-    host: '127.0.0.1:3080',
-    origin: 'http://127.0.0.1:3080',
-    'sec-fetch-site': 'same-origin',
-  },
-) {
-  return { socket: { remoteAddress }, headers }
-}
-
-describe('native dialog request trust', () => {
-  it('accepts loopback same-origin browser requests', () => {
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1'))).toBe(true)
-    expect(isTrustedNativeDialogRequest(request('::1', {
-      host: '[::1]:3080', origin: 'http://[::1]:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(true)
-    expect(isTrustedNativeDialogRequest(request('::ffff:127.0.0.1'))).toBe(true)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: 'localhost:3080', origin: 'http://localhost:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(true)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.2', {
-      host: '127.0.0.2:3080', origin: 'https://127.0.0.2:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(true)
-  })
-
-  it('rejects remote sockets and requests without matching browser metadata', () => {
-    expect(isTrustedNativeDialogRequest(request('192.168.1.5'))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request(undefined))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: '127.0.0.1:3080', origin: 'http://evil.example', 'sec-fetch-site': 'cross-site',
-    }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: '127.0.0.1:3080', origin: 'http://localhost:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', { host: '127.0.0.1:3080' }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      origin: 'http://127.0.0.1:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: 'attacker.example:3080', origin: 'http://attacker.example:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: '127.0.0.1:3080', origin: 'ftp://127.0.0.1:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: '127.999.0.1:3080', origin: 'http://127.999.0.1:3080', 'sec-fetch-site': 'same-origin',
-    }))).toBe(false)
-    expect(isTrustedNativeDialogRequest(request('127.0.0.1', {
-      host: '[invalid', origin: 'http://[invalid', 'sec-fetch-site': 'same-origin',
-    }))).toBe(false)
-  })
-})

+ 75 - 35
packages/client/connection/tests/node-half.spec.ts

@@ -1,4 +1,6 @@
 /** Node half: registers the /api prefix route bridging to the api gateway. */
+import { EventEmitter } from 'node:events'
+import { Readable } from 'node:stream'
 import { Context } from 'cordis'
 import { describe, expect, it } from 'vitest'
 import type { IncomingMessage, ServerResponse } from 'node:http'
@@ -6,46 +8,84 @@ import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
 import type { HttpServerService, WebRoute } from '@deepseek-ai/dsh-host-webserver'
 import { API_PATH, apply, inject } from '../src/index.ts'
 
+/** Structural httpServer fake: the plugin only touches register(). */
+function fakeHttpServer(routes: WebRoute[]): Pick<HttpServerService, 'register' | 'tapIndex' | 'port'> {
+  return {
+    register(route) {
+      routes.push(route)
+      return () => { routes.splice(routes.indexOf(route), 1) }
+    },
+    tapIndex: () => () => {},
+    port: 0,
+  }
+}
+
+/** Bodyless GET carrying the given headers (enough for the trust fence + bridge). */
+function fakeRequest(headers: Record<string, string>): IncomingMessage {
+  const request = Readable.from([]) as unknown as IncomingMessage
+  Object.assign(request, { url: `${API_PATH}/session.list`, method: 'GET', headers })
+  return request
+}
+
+/** Response recorder compatible with both the fence's short-circuit and the bridge. */
+function fakeResponse(): { response: ServerResponse; state: { status?: number; body?: unknown } } {
+  const state: { status?: number; body?: unknown } = {}
+  const response = Object.assign(new EventEmitter(), {
+    writableEnded: false,
+    writeHead(value: number) { state.status = value; return this },
+    write() { return true },
+    end(this: { writableEnded: boolean }, value?: unknown) {
+      if (value !== undefined) state.body = value
+      this.writableEnded = true
+      return this
+    },
+  }) as unknown as ServerResponse
+  return { response, state }
+}
+
+async function mounted(config?: { trustedHosts?: string[] }): Promise<{ routes: WebRoute[]; dispose: () => Promise<void> }> {
+  const ctx = new Context()
+  const routes: WebRoute[] = []
+  ctx.provide('httpServer', fakeHttpServer(routes) as HttpServerService)
+  ctx.provide('apiProxy', {} as unknown as ApiProxy)
+  const fiber = ctx.plugin({ inject: [...inject], apply }, config)
+  await fiber.await()
+  return { routes, dispose: () => fiber.dispose() }
+}
+
 describe('connection node half', () => {
   it('registers the /api prefix route and removes it with the fiber', async () => {
-    const ctx = new Context()
-    const routes: WebRoute[] = []
-    // Structural fake: the plugin only touches register(); the service class
-    // carries private state a literal cannot (and need not) reproduce.
-    const httpServer: Pick<HttpServerService, 'register' | 'tapIndex' | 'port'> = {
-      register(route) {
-        routes.push(route)
-        return () => { routes.splice(routes.indexOf(route), 1) }
-      },
-      tapIndex: () => () => {},
-      port: 0,
-    }
-    ctx.provide('httpServer', httpServer as HttpServerService)
-    ctx.provide('apiProxy', {} as unknown as ApiProxy)
-
-    const fiber = ctx.plugin({ inject: [...inject], apply })
-    await fiber.await()
+    const { routes, dispose } = await mounted()
     expect(routes).toHaveLength(1)
     expect(routes[0]).toMatchObject({ kind: 'prefix', path: API_PATH })
+    await dispose()
+    expect(routes).toHaveLength(0)
+  })
 
-    let status: number | undefined
-    let body: unknown
-    const deniedRequest = {
-      url: '/api/host.pickDirectory',
-      headers: {
-        host: 'harness.example', origin: 'http://harness.example', 'sec-fetch-site': 'same-origin',
-      },
-      socket: { remoteAddress: '192.168.1.8' },
-    } as unknown as IncomingMessage
-    const deniedResponse = {
-      writeHead(value: number) { status = value; return this },
-      end(value?: unknown) { body = value; return this },
-    } as unknown as ServerResponse
-    await routes[0]!.handler(deniedRequest, deniedResponse)
-    expect(status).toBe(403)
-    expect(body).toBe('forbidden')
+  it('refuses an untrusted Host on any /api path before the bridge runs', async () => {
+    const { routes, dispose } = await mounted()
+    const { response, state } = fakeResponse()
+    await routes[0]!.handler(fakeRequest({
+      host: 'harness.example', origin: 'http://harness.example', 'sec-fetch-site': 'same-origin',
+    }), response)
+    expect(state.status).toBe(403)
+    expect(state.body).toBe('forbidden')
+    await dispose()
+  })
 
-    await fiber.dispose()
-    expect(routes).toHaveLength(0)
+  it('passes loopback and declared-authority requests through to the bridge', async () => {
+    const { routes, dispose } = await mounted({ trustedHosts: ['harness.example:3080'] })
+    // Loopback, no browser markers (curl shape): the fence passes; the carrier
+    // answers 404 for a GET unary path — proof the bridge ran.
+    const loopback = fakeResponse()
+    await routes[0]!.handler(fakeRequest({ host: '127.0.0.1:3080' }), loopback.response)
+    expect(loopback.state.status).toBe(404)
+    // Declared public authority, same-origin browser shape.
+    const declared = fakeResponse()
+    await routes[0]!.handler(fakeRequest({
+      host: 'harness.example:3080', origin: 'http://harness.example:3080', 'sec-fetch-site': 'same-origin',
+    }), declared.response)
+    expect(declared.state.status).toBe(404)
+    await dispose()
   })
 })

+ 2 - 2
packages/host/apiproxy/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md
-README.md: 63294100cd0dc62f9822a3ca9678c1034880169f
-README.zh.md: 251b4b0356da5f1fb518d133a92f484da957b951
+README.md: 2f51aa23e2639e2e98dfdd8aaf71e807d641c3dc
+README.zh.md: 687e60879702a762d9e85295789b77daea4bd4ac

+ 1 - 1
packages/host/apiproxy/README.md

@@ -16,7 +16,7 @@ Session model routing is a session-domain contract. `session.models` returns the
 
 Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `workspace.delete` removes only the Workspace registration, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed`, `host/workspace-removed`, plus `host/session-added` carry committed increments in either arrival order. Registration deletion preserves the directory and session logs; its Sessions remain in `session.list` and become Ungrouped. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`.
 
-`host.pickDirectory` opens one native directory picker and returns its selected path, or `null` when the user cancels. Its host implementation invokes platform tools without a shell: `osascript` on macOS, an STA PowerShell `FolderBrowserDialog` on Windows, and Zenity with a KDialog fallback on Linux. The picker function is injectable for tests. This user-paced method is the sole unary call exempt from the default 30-second timeout; caller and connection aborts still propagate to the native process. The browser carrier separately restricts this privileged method to loopback, same-origin requests.
+`host.pickDirectory` opens one native directory picker and returns its selected path, or `null` when the user cancels. Its host implementation invokes platform tools without a shell: `osascript` on macOS, an STA PowerShell `FolderBrowserDialog` on Windows, and Zenity with a KDialog fallback on Linux. The picker function is injectable for tests. This user-paced method is the sole unary call exempt from the default 30-second timeout; caller and connection aborts still propagate to the native process. The browser carrier's prefix-wide trust fence (dsh-client-connection) covers this method like every other `/api` request.
 
 `session.history` pages on message boundaries, and its tail page (no `beforeSeq`) carries two session-level extras the page window cannot supply: the in-flight partial's chunk events, and `todos` — the latest `todo/write` whole-list projection over the full log. Older pages omit `todos` because the projection is session-level, not per-page; a tail response that omits it means the whole log holds no `todo/write`, so clients read the absent field as the empty plan rather than as unchanged state.
 

+ 1 - 1
packages/host/apiproxy/README.zh.md

@@ -16,7 +16,7 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时
 
 Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create` 会创建唯一名称或接纳现有目录,`workspace.delete` 只移除 Workspace 注册记录,`session.create` 接受可选的预分配 Session id,`host/workspace-changed`、`host/workspace-removed` 与 `host/session-added` 则以任意到达顺序携带已提交的增量。删除注册记录会保留目录和会话日志;相关 Session 仍留在 `session.list` 中,并进入 Ungrouped。`SessionSummary.blank` 与 `host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank,并以 `session.list` 作为重连权威;冷会话摘要永远不是空白:惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。
 
-`host.pickDirectory` 会打开一个原生目录选择器并返回选中的路径;用户取消时返回 `null`。宿主实现不经 shell 调用平台工具:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity,并以 KDialog 作为回退。选择器函数可在测试中注入。该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用;调用方发出的中止信号和连接中止仍会传播至原生进程。浏览器载体另行将这一特权方法限制为仅接受来自回环地址的同源请求
+`host.pickDirectory` 会打开一个原生目录选择器并返回选中的路径;用户取消时返回 `null`。宿主实现不经 shell 调用平台工具:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity,并以 KDialog 作为回退。选择器函数可在测试中注入。该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用;调用方发出的中止信号和连接中止仍会传播至原生进程。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖该方法
 
 `session.history` 按消息边界分页,其尾页(不带 `beforeSeq`)额外携带两项页窗口本身无法提供的会话级数据:进行中局部消息的 chunk 事件,以及 `todos`——整份日志上最后一次 `todo/write` 的整表投影。较早的页面不带 `todos`,因为该投影是会话级而非分页级的;尾页响应缺少该字段意味着整份日志中没有任何 `todo/write`,因此客户端要把缺失字段读作空计划,而不是读作「状态未变」。
 

+ 3 - 0
pnpm-lock.yaml

@@ -797,6 +797,9 @@ importers:
       '@deepseek-ai/dsh-tools':
         specifier: workspace:^
         version: link:../../core/tools
+      schemastery:
+        specifier: ^3.18.0
+        version: 3.18.0
     devDependencies:
       '@deepseek-ai/dsh-host-webserver':
         specifier: workspace:^