diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index 525f2cdd33..b7f69935ec 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -9,14 +9,14 @@ en: 01293500639c9d79 zh: 6d19e4843955c811 /agent-note-browser-launch-token-authentication/decision: - en: 51885594bdeb6f0c - zh: 9c2e41ad79ccdd08 + en: 0c437d201b8668d5 + zh: 2c1b3e67b38a5012 /agent-note-browser-launch-token-authentication/verification: - en: 189b36d0fc5f3a17 - zh: 08993cb585204fc0 + en: 51fe0a5b45693654 + zh: 69c82207975fa421 /agent-note-browser-launch-token-authentication/alternatives-considered: en: 5275c87f19fe6eee zh: ccb922367c4bb3e2 /agent-note-browser-launch-token-authentication/consequences: - en: af55274a2f345cdd - zh: 4d1810141ef03bae + en: 5d69529b50c1ff32 + zh: 5fc371b5cde4783e diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index c845053a63..2a8d5e5319 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -10,15 +10,15 @@ The Web Host runs tool-capable Sessions with the current operating-system user's ## Decision -Browser callers follow this decision; independent CLI/MCP admission is owned by the [API connect decision](2026-10-09-operator-scoped-connect-handshake.md). +The default browser Token implementation follows this decision and is provided by [`dsh-host-authentication-token`](../../../../packages/host/authentication-token/README.md); independent CLI/MCP admission is owned by the [API connect decision](2026-10-09-operator-scoped-connect-handshake.md). The [Provider decision](2026-11-07-browser-authentication-providers.md) defines independent authentication ownership and equal Token, Desktop, and Remote extension points while retaining this credential protocol; the Remote product itself is not implemented. -`dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires the same browser session; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without a valid browser session receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md). +`dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires an authenticated Peer; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without valid credentials receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md). -Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `./`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `./`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. +The Token plugin generates one random launch token per Host root and retains it across plugin reloads. It contributes a signed entry URL through `webserver/entry-url`; WebApp supplies the ordinary base address and owns printing and opening entries once per root application according to its startup configuration. The plugin handles the root exchange through `webserver/request`: `GET /?token=...` exchanges the process token for a cookie and redirects to clean `./`. An obsolete token paired with a valid default cookie also redirects to clean `./`. The plugin registers its Cookie verifier with `connection.authentication`, and `frontend-static` uses the admitted Peer to render the index. Default-token requests with missing or invalid credentials receive the minimal 401 response; static non-index assets remain public. API token handling remains with the independent `/connect` handshake. The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. The HTTP listener omits `Secure`. There is no logout operation. -The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection loads or creates the record during activation and retains the secret for synchronous request verification. An active Connection continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. +The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. The Token plugin loads or creates the record during activation and retains the secret for synchronous request verification. An active Token plugin continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker. @@ -26,7 +26,7 @@ The shipped CLI accepts concrete local bind addresses but rejects wildcard addre ## Verification -Unit coverage pins process-token retention across Connection reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for generic RPC, Typert Remote HTTP, exact Fetch routes, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `settings/describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. +Unit coverage pins process-token retention across Token plugin reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for generic RPC, Typert Remote HTTP, exact Fetch routes, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, the Token plugin, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `settings/describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. ## Alternatives considered @@ -44,7 +44,7 @@ Unit coverage pins process-token retention across Connection reloads, one secret Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application exposes after Session creation. `Host` does not grant a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set. -The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Connection intentionally avoids credential-provider work on each request. An HTTP listener permits plaintext cookie transmission if its authority is reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. +The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Token verifier uses its loaded secret for each request. An HTTP listener permits plaintext cookie transmission if its authority is reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. The decision partially supersedes the authentication deferral and unauthenticated non-loopback consequences in the [browser trust note](2026-07-28-api-browser-trust-boundary.md). That note remains active authority for media-type, Host, Origin, Fetch-Metadata, and configured-authority validation. No active Agent Note is archived: the overlap is partial and both security rules retain future decision value. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index 781a1d12a0..14ac57ae33 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -10,15 +10,15 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session ## 决策 -浏览器调用方遵循本决策;独立 CLI/MCP 接纳由 [API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)定义。 +默认浏览器 Token 实现遵循本决策,由 [`dsh-host-authentication-token`](../../../../packages/host/authentication-token/README.zh.md) 提供;独立 CLI/MCP 接纳由 [API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)定义。[Provider 决策](2026-11-07-browser-authentication-providers.zh.md)定义独立认证归属和平级 Token、Desktop、Remote 扩展接入,同时保留本凭据协议;Remote 产品本身尚未实现。 -`dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求同一个浏览器会话;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效浏览器会话时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。 +`dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求已认证 Peer;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效凭据时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。 -每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `./`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `./`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 +Token 插件为每个 Host 根生成一个随机启动令牌,并跨插件重载保留。它通过 `webserver/entry-url` 贡献带签名的入口 URL;WebApp 提供普通基地址,并按自身启动配置负责在每个根应用中打印和打开入口一次。插件通过 `webserver/request` 处理根路径交换:`GET /?token=...` 把进程令牌交换为 cookie,再重定向到干净的 `./`。过时令牌同时带有有效默认 cookie 时,也重定向到干净的 `./`。插件向 `connection.authentication` 注册 Cookie 验证器,`frontend-static` 使用准入 Peer 渲染 index。默认 Token 请求缺失或携带无效凭据时得到最小 401 响应;非 index 静态资产保持公开。API Token 处理仍归独立的 `/connect` 握手。 cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。HTTP 监听器不设置 `Secure`。这里没有 logout 操作。 -HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Connection 继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 +HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Token 插件在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Token 插件继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。 @@ -26,7 +26,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` ## 验证 -单元覆盖 Connection 重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定通用 RPC、Typert Remote HTTP、精确 Fetch 路由和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `settings/describe`,观测新的进程令牌,并在重启后复用旧 cookie。 +单元覆盖 Token 插件重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定通用 RPC、Typert Remote HTTP、精确 Fetch 路由和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、Token 插件、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `settings/describe`,观测新的进程令牌,并在重启后复用旧 cookie。 ## 曾考虑的替代方案 @@ -44,7 +44,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。 -持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Connection 刻意避免在每个请求上访问凭据提供方。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 +持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Token 验证器在每个请求上使用已加载的密钥。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。 diff --git a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml index f95418e8be..e4de02f655 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.i18n.yaml @@ -72,8 +72,8 @@ en: 607a1afd89892d15 zh: a0aa85124340458c /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/security-and-validation: - en: 2426665452a6a37b - zh: 282572d66e17a237 + en: 0683589c4c144620 + zh: 29c23acf6d6fef51 /agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/decision/in-process-and-worker-carriers: en: df4ae60d8403cdbb zh: 70c6024a2a9a1e84 diff --git a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md index d6f2c2b448..d4ef849456 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md +++ b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.md @@ -305,7 +305,7 @@ Credit frames wait until a consumer that needs sustained high-volume uplink appe | Item | Rule | | --- | --- | -| Authentication | Same as today: `connection.requestRejection(req)` at upgrade; descriptor and lookup-parameter validation at open. Uplink items belong to an already authenticated stream and are not authenticated again | +| Authentication | WebServer admission supplies the Peer at upgrade; descriptor and lookup-parameter validation runs at open. Uplink items belong to an already authenticated stream and are not authenticated again | | Peer | Admitted at upgrade as one `PeerScope`; `invocation.peer` of every stream on that socket is that Peer | | Item validation | With an uplink codec, every item is decoded strictly, and a failure fails the whole stream with the existing `gateway/input-invalid` (details `{ endpoint, field: 'uplink' }`); without a codec, only JSON-safety validation applies | | Frame size | A single frame keeps the `maxPayload` of `ws`; the inbox limit bounds the accumulated total | diff --git a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md index f946515b7a..8c72fa3cb3 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-remote-duplex-stream.zh.md @@ -305,7 +305,7 @@ credit 帧留待需要持续大流量上行的消费者出现时再加;inbox | 项 | 规则 | | --- | --- | -| 鉴权 | 与今天相同:升级时 `connection.requestRejection(req)`;打开时描述符与查找参数校验。上行项属于一条已鉴权的流,不重复鉴权 | +| 鉴权 | 升级时由 WebServer 准入提供 Peer;打开时校验描述符与查找参数。上行项属于一条已鉴权的流,不重复鉴权 | | Peer | 升级时接纳为一个 `PeerScope`,该 socket 上所有流的 `invocation.peer` 都是它 | | 项校验 | 有 uplink codec 时逐项严格解码,失败即整条流以既有的 `gateway/input-invalid` 失败(details `{ endpoint, field: 'uplink' }`);无 codec 时只做 JSON 安全校验 | | 帧大小 | 单帧沿用 `ws` 的 `maxPayload`;inbox 上限限制累计量 | diff --git a/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.i18n.yaml index 10847a2adb..60f9d8929a 100644 --- a/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.i18n.yaml @@ -9,8 +9,8 @@ en: 3658160e034e0e58 zh: 980d922aded8713b /agent-note-peer-scoped-connect-handshake/decision: - en: 414dfe949a53c4d9 - zh: 7e6efdd57f2eb240 + en: 6d84e6633c7f2aa8 + zh: 11d09a4efb5cf570 /agent-note-peer-scoped-connect-handshake/decision/admission-and-ownership: en: 95ad4c8c433fdc9b zh: 379ccd5e077d7dee @@ -27,5 +27,5 @@ en: 81ce03ab4e1fd0d4 zh: c2729e7e2db56f67 /agent-note-peer-scoped-connect-handshake/consequences: - en: 91f5f80f733c174c - zh: 76cbb31b0d2e8764 + en: 52b687e9b5906c59 + zh: 9eb9c740e2873f70 diff --git a/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.md b/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.md index 9211aa6d43..3aa4f92cd3 100644 --- a/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.md +++ b/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.md @@ -10,7 +10,7 @@ Automatically subscribing automation clients to forwarded events lets method-onl ## Decision -Browsers retain their existing signed Cookie, root launch-token exchange, shared `connection.browserPeer` with owner principal and `interactions: 'answer'`, and recovery behavior. Only API callers create independent Peers through `GET /connect?token=&interactions=answer|none`. The endpoint is API-only, defaults to `none`, rejects invalid or repeated declarations with 400, and retains Host/Origin checks and token authentication. It returns 302 with the Remote Mux destination and an API Cookie. +Browsers retain their existing signed Cookie, root launch-token exchange, the Token Provider's shared Peer with owner principal and `interactions: 'answer'`, and recovery behavior. Only API callers create independent Peers through `GET /connect?token=&interactions=answer|none`. The endpoint is API-only, defaults to `none`, rejects invalid or repeated declarations with 400, and retains Host/Origin checks and token authentication. It returns 302 with the Remote Mux destination and an API Cookie. ### Admission and ownership @@ -52,4 +52,4 @@ The [recorded approval scenario](../../../../apps/web/tests/approval-composer.e2 Unconnected API records need not be promptly reclaimed; resource-heavy additions to idle Peers require revisiting that choice. API Cookies cannot restore a Peer after its socket closes or the Host restarts. Browser Cookie format and authentication behavior remain unchanged, with no reauthentication migration. API and browser Cookies use the same authority-specific name, so API callers keep their own Cookie storage rather than exchanging credentials in a shared browser jar. Any launch-token holder may request `answer`; this is interaction participation, not user isolation. -The [duplex-stream decision](2026-09-19-remote-duplex-stream.md) retains Peer scopes and stream framing. The [browser authentication decision](2026-08-24-browser-token-authentication.md) retains browser token, signature, authority, and lifetime semantics; only independent API admission is added here. Both records remain active. +The [duplex-stream decision](2026-09-19-remote-duplex-stream.md) retains Peer scopes and stream framing. The [browser authentication decision](2026-08-24-browser-token-authentication.md) retains browser token, signature, authority, and lifetime semantics; only independent API admission is added here. Both records remain active. The [Provider integration](2026-11-07-browser-authentication-development.md) owns the current registration and Socket-middleware placement without replacing this protocol and lifetime decision. diff --git a/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.zh.md b/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.zh.md index e7d8f7a4ea..1ad59570f1 100644 --- a/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-09-operator-scoped-connect-handshake.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -浏览器保留现有签名 Cookie、根路径 launch token 交换、共享 `connection.browserPeer` 和恢复行为。只有 API 调用方通过 `GET /connect?token=&interactions=answer|none` 创建独立 Peer。该端点仅供 API 使用,默认 `none`,非法或重复声明返回 400,并保留 Host/Origin 检查和 token 认证。它返回 302、Remote Mux 目标地址和 API Cookie。 +浏览器保留现有签名 Cookie、根路径 launch token 交换、Token Provider 持有的共享 owner Peer(`interactions: 'answer'`)和恢复行为。只有 API 调用方通过 `GET /connect?token=&interactions=answer|none` 创建独立 Peer。该端点仅供 API 使用,默认 `none`,非法或重复声明返回 400,并保留 Host/Origin 检查和 token 认证。它返回 302、Remote Mux 目标地址和 API Cookie。 ### 接纳与所有权 @@ -52,4 +52,4 @@ Connection 测试覆盖 API 发布、Cookie 校验、闲置保留、连接所有 未建联的 API 记录不要求及时回收;若为空闲 Peer 增加重资源,必须重新评估这一取舍。连接关闭或 Host 重启后,API Cookie 不能恢复 Peer。浏览器 Cookie 格式与认证行为保持不变,无需重新认证迁移。API 与浏览器 Cookie 使用同一 authority 专属名称,因此 API 调用方维护自己的 Cookie 存储,不在共享浏览器 Cookie jar 中交换凭证。任何 launch token 持有者都可以请求 `answer`;这是交互参与,不是用户隔离。 -[双工流决策](2026-09-19-remote-duplex-stream.zh.md)继续定义 Peer 作用域和流帧格式。[浏览器认证决策](2026-08-24-browser-token-authentication.zh.md)保留浏览器 token、签名、authority 与有效期语义;本记录只增加独立 API 接纳。两份既有记录继续保留。 +[双工流决策](2026-09-19-remote-duplex-stream.zh.md)继续定义 Peer 作用域和流帧格式。[浏览器认证决策](2026-08-24-browser-token-authentication.zh.md)保留浏览器 token、签名、authority 与有效期语义;本记录只增加独立 API 接纳。两份既有记录继续保留。[Provider 接入说明](2026-11-07-browser-authentication-development.zh.md)拥有当前注册与 Socket 中间件的实现位置,不取代本协议与生命周期决策。 diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml new file mode 100644 index 0000000000..4fefcfd5c3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for 2026-11-07-browser-authentication-development.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md +/agent-note-authentication-provider-integration: + en: 1a29efbb24021a72 + zh: be3ad79af7975a72 +/agent-note-authentication-provider-integration/problem: + en: 670cfd5061a9aa5a + zh: 98598c1e45236ed2 +/agent-note-authentication-provider-integration/decision: + en: a15c7c13f167e5ac + zh: a15c7c13f167e5ac +/agent-note-authentication-provider-integration/decision/register-a-provider-and-own-its-peer: + en: 7305dc1791116cf6 + zh: f23cd0b8161522ee +/agent-note-authentication-provider-integration/decision/declare-route-admission-and-consume-the-selected-peer: + en: e2b17a8dff46e81c + zh: 2391ed8fdf502a30 +/agent-note-authentication-provider-integration/decision/use-scoped-webserver-events: + en: 3f191940167f3f9e + zh: 6e4f20d1f66f5454 +/agent-note-authentication-provider-integration/decision/keep-socket-policy-with-the-issuing-product: + en: 59235b955e65e342 + zh: 76d9314d0a738438 +/agent-note-authentication-provider-integration/decision/let-webapp-publish-complete-entry-urls: + en: 0676f301d5aec364 + zh: 0ef43eba7bfe2f01 +/agent-note-authentication-provider-integration/testing: + en: c783cb006f9962a4 + zh: 79bf36b25665e49c +/agent-note-authentication-provider-integration/alternatives-considered: + en: 868953274abd81e8 + zh: 1b2890de876a6db6 +/agent-note-authentication-provider-integration/consequences: + en: cf654878d39ce4bc + zh: 435687a8da20f294 diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md new file mode 100644 index 0000000000..d2d688ed61 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.md @@ -0,0 +1,141 @@ +# Agent Note: Authentication Provider integration + +Status: implemented + +English | [中文](2026-11-07-browser-authentication-development.zh.md) + +## Problem + +In the built-in authentication design, Connection combined BrowserAuth with its transport API, and route owners called its admission helpers. WebApp obtained a tokenized address through Connection. Splitting credential implementations requires concrete registration, route, event, and startup usage that does not put Token knowledge back into a transport or protocol handler. + +The [Provider decision](2026-11-07-browser-authentication-providers.md) owns the rationale, credential compatibility, and equal treatment of Token, Desktop, and future Remote implementations. This note owns their integration with the final APIs. + +## Decision + +### Register a Provider and own its Peer + +The Connection plugin provides the independent nested `connection.authentication` Service. A Provider plugin injects both `connection` and `connection.authentication`: the former creates Peers, while the latter owns registration and credential verification. The access path is a real Cordis service, not a getter constructing a temporary registry object. + +This complete function-plugin example receives a trusted in-process verifier and principal from its Host. Its `Config.verify` is an illustrative application input, not a new DSH API or a substitute for implementing the credential algorithm. + +```ts +import type { Context } from '@deepseek-ai/cordis' +import type { ConnectionTrustRequest, Principal } from '@deepseek-ai/dsh-client-connection' + +export const name = 'example-authentication' +export const inject = ['connection', 'connection.authentication'] + +export interface Config { + principal: Principal + verify(request: ConnectionTrustRequest): boolean +} + +export function apply(ctx: Context, config: Config): void { + const peer = ctx.connection.createPeer({ principal: config.principal }) + ctx.connection.authentication.register({ + authenticate(request) { + return config.verify(request) ? peer : undefined + }, + }) +} +``` + +`createPeer` owns the Peer under the calling plugin scope; `register` owns the registration under that same caller scope. A shared-identity Provider retains one Peer as above. A session-based Provider instead retains its own credential-to-Peer records and returns the corresponding existing Peer. The Host fixes `principal` and optional `interactions` at creation; neither is a client-selected authorization claim. + +`register` returns an asynchronous disposer whose call synchronously withdraws the record. Authentication snapshots registration order, skips records withdrawn during verification, and rechecks a returned Peer and the request before accepting. New registrations participate in subsequent requests. `authenticate` returns the first live Peer,401 for ordinary refusal, or503 when a verifier failed and none succeeded. Source rejection remains Connection's separate403 decision. The [implementation](../../../../packages/client/connection/src/authentication.ts) contains these lifecycle checks. + +### Declare route admission and consume the selected Peer + +`register`, `registerFallback`, and `registerUpgrade` accept `auth: 'anonymous' | 'required' | 'deny'` or a synchronous selector. The default is `required`. WebServer matches first, applies policy, obtains Connection's source and credential decision, and passes the selected Peer to the handler. `deny` rejects without invoking authentication; with no authorization listener, `required` returns503 and `anonymous` permits access. + +The example below registers ordinary business handlers. The Host supplies `Config.upgrade`, its existing protocol implementation; it is not another framework operation. The HTTP assertion reflects this route's `required` policy, while the shared handler type also supports anonymous routes with no Peer. + +```ts +import type { Context } from '@deepseek-ai/cordis' +import type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' + +export const name = 'example-protected-routes' +export const inject = ['webServer'] + +export interface Config { + upgrade: WebUpgradeRoute['handler'] +} + +export function apply(ctx: Context, config: Config): void { + ctx.effect(() => ctx.webServer.register({ + kind: 'exact', + path: '/identity', + auth: 'required', + handler(_req, res, peer) { + res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }) + res.end(peer!.id) + }, + })) + ctx.effect(() => ctx.webServer.registerUpgrade({ + path: '/example/socket', + auth: 'required', + handler: config.upgrade, + })) +} +``` + +HTTP handlers receive `(req, res, peer?)`, upgrade handlers receive `(req, socket, head, peer?)`, and resources retain `resource(request, peer?)`. Business handlers do not run another Provider pass. Direct administration routes outside Gateway, including Inspector and open-in-app, require an owner Peer before accessing Host resources. Trusted in-process `readResource(request, peer)` keeps its explicit Peer without network source or credential checks, but still honors `deny`. Admission failures carry `Cache-Control: no-store`. + +### Use scoped WebServer events + +Every WebServer event has the corresponding WebServer as its Cordis thisArg. Request dispatch uses the service instance; WebApp entry collection passes `ctx.webServer`. Ordinary listeners match the `webServer` isolation of that subject, including the existing index-injection event. `{ global: true }` explicitly receives events across service isolations in the same application. Peer data does not select event listeners. The [WebServer reference](../../../../packages/host/webserver/README.md) defines custom-carrier obligations. + +| Event | Mode | Final integration | +|---|---|---| +| `webserver/request` | waterfall | Runs before route selection; Token exchanges root Token queries, and the account plugin handles its validated OAuth callback | +| `webserver/authorize` | bail | Resolves the matched route's source and credential admission; the first decision wins | +| `webserver/upgrade` | waterfall | Runs after admission and before the protocol handler, carrying the already selected Peer | +| `webserver/index-inject` | emit | Collects page or Worker startup data for the supplied Peer within the server isolation | +| `webserver/entry-url` | emit | Collects complete entry URLs for the supplied base address within the server isolation | + +Waterfall listeners own the response or Socket when they handle a request; otherwise they await `next()`. Exceptions are contained by the carrier and end that response or Socket. Source policy is not disabled for every anonymous route to accommodate a login protocol. + +The account plugin registers a temporary callback listener before generic admission. It matches the initiating redirect URI's authority and exact path, then preserves GET, single state/code values, constant-time state comparison, active-attempt checks, expiry, cancellation, and S256 PKCE. Thus a valid cross-site browser return can finish without bypassing those checks or weakening unrelated anonymous routes. The listener leaves with the attempt; it does not import a WebServer implementation helper. + +### Keep Socket policy with the issuing product + +Token's listener sits beside its `/connect` route and acts only on `/api/remote.mux`. It recognizes its own API Peer by map identity, rejects a second mux Socket with409, and synchronously removes the credential before awaiting Peer and Socket cleanup. Closing an Inspector CDP Socket does not claim or revoke that API session. Other Providers retain their own lifetime policies; Gateway only performs protocol upgrade with the supplied Peer. + +An upgrade fixes the Peer for that connection. Later HTTP requests authenticate again. Token's shared browser Peer survives individual Socket closure; an API Peer follows its existing mux lifetime. Already-admitted unary calls retain their cancellation scope. The [mux regression](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts) and [API connect decision](2026-10-09-operator-scoped-connect-handshake.md) cover this distinction. + +### Let WebApp publish complete entry URLs + +WebApp keeps `publicUrl`, `printUrl`, and `openBrowser`; both output flags default true. After Loader settlement and startup audit, it emits `webserver/entry-url` with its WebServer subject, ordinary base URL, and an initially empty `WebEntryUrl[]`. Each entry carries `label`, complete `url`, and boolean `open`. + +Token contributes its signed `dsh web` URL without reading WebApp services. A Provider with no user-facing entry contributes nothing; another product can contribute its own label and complete URL. WebApp prints each `label: url` line when enabled, and opens only the first `open: true` entry when browser opening is enabled outside SSH. An empty list causes no output or browser opening. The process credential remains sensitive even though the integration exposes no raw Token getter. + +Desktop's parent owns a fresh private credential per Host process and delivers it before ready. The Desktop Provider creates its Peer and registers verification through the same authentication Service. Electron uses its locally assembled `authenticationCookie`; runtime smoke and other parent-process consumers do not attempt a Token exchange using the ordinary ready URL. Renderer startup data and the wire ready message contain no private credential. + +## Testing + +| Affected behavior | Before | Final behavior and coverage | +|---|---|---| +| Provider registration | Only built-in BrowserAuth supplied network identity | Ordered independent verifiers select one live Peer; scope unload, verifier failure, and cancellation are covered by [authentication tests](../../../../packages/client/connection/tests/authentication.host.spec.ts) | +| HTTP and upgrade integration | Consumers called Connection admission | Route auth supplies the Peer once; real [Provider transport tests](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts) exercise both carriers | +| Server isolation | Route tables were per instance; index injection was root-wide | All five events use the WebServer subject; [server](../../../../packages/host/webserver/tests/event-isolation.host.spec.ts) and [application](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts) tests cover ordinary and global listeners and a preserved external Host | +| Browser OAuth return | The callback validated state and PKCE | The scoped pre-route callback retains validation and accepts real cross-site navigation; [account tests](../../../../packages/credentials/deepseek-account/tests/account.spec.ts) retain wrong-Host and SSH-forwarding coverage, and [Chromium](../../../../apps/web/tests/account-login.e2e.ts) asserts the actual Fetch Metadata header | +| Startup output | WebApp printed/opened one Connection-produced login URL | [Startup tests](../../../../packages/bundle/web-app/tests/startup.host.spec.ts) cover ordered entries, first eligible opening, empty lists, readiness and SSH suppression | +| Desktop runtime consumers | A tokenized ready URL was exchanged for a Cookie | [Runtime smoke tests](../../../../apps/desktop/tests/smoke-runtime.spec.ts) use the private Cookie on the HTTP probes; [built Remote tests](../../../../packages/api/remotes/tests/built-lib.e2e.ts) collect the current Provider's entry and pass the admitted Peer | + +## Alternatives considered + +**Keep authentication behind per-request wrappers on Connection.** A separately registered Service exposes its ownership and required injection directly; it does not allocate a facade each time a consumer reads authentication. + +**Add another route table or a request-context container.** Existing WebServer registrations already own dispatch, and Peer is the identity consumed downstream. Route policy and a trailing Peer parameter keep those owners intact. + +**Pass an extra WebServer field in every request.** Cordis already supports a service subject and isolation filter. Using that mechanism also scopes page injection and entry collection without adding payload fields. + +**Give Token the WebApp address service or browser opener.** That creates a reverse dependency on the composing bundle. WebApp owns publication timing and actions; Providers contribute complete entries through the shared event. + +## Consequences + +Credential implementations need no Gateway change, but custom carriers must emit events with their WebServer subject and pass the admitted Peer to protocol handlers. Plugins consuming the nested authentication service declare `connection.authentication` in their injections. Explicitly global event listeners remain responsible for whether sharing data across server instances is appropriate. + +Removing a Provider registration and disposing its Peer are distinct operations. A product that shares one Peer also shares its termination scope; a product with independent credentials owns its own Peer records and revocation policy. The integration adds neither a universal Socket policy nor another authentication privilege tier. + +The [Provider decision](2026-11-07-browser-authentication-providers.md) owns protocol compatibility and deployment consequences. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md) owns manual configuration migration and carrier updates; this record describes the implemented integration rather than a future Remote product. diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md new file mode 100644 index 0000000000..15919e55f7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-development.zh.md @@ -0,0 +1,141 @@ +# Agent Note: 认证 Provider 接入 + +Status: implemented + +[English](2026-11-07-browser-authentication-development.md) | 中文 + +## Problem + +在内置认证设计中,Connection 同时包含 BrowserAuth 和传输 API,路由 owner 调用它的准入辅助方法。WebApp 通过 Connection 取得带 Token 的地址。拆分凭据实现需要明确的注册、路由、事件和启动用法,不能把 Token 知识重新放回传输或协议 handler。 + +[Provider 决策](2026-11-07-browser-authentication-providers.zh.md)拥有动机、凭据兼容性,以及 Token、Desktop 和未来 Remote 实现的平级处理规则。本文记录它们与最终 API 的接线。 + +## Decision + +### 注册 Provider 并持有 Peer + +Connection 插件提供独立嵌套服务 `connection.authentication`。Provider 插件同时注入 `connection` 和 `connection.authentication`:前者创建 Peer,后者拥有注册与凭据验证。该访问路径是真正的 Cordis 服务,不是构造临时注册表对象的 getter。 + +下面的完整函数插件示例由 Host 提供可信进程内验证器和 principal。其中 `Config.verify` 是示例的应用输入,不是新 DSH API,也不代替具体凭据算法的实现。 + +```ts +import type { Context } from '@deepseek-ai/cordis' +import type { ConnectionTrustRequest, Principal } from '@deepseek-ai/dsh-client-connection' + +export const name = 'example-authentication' +export const inject = ['connection', 'connection.authentication'] + +export interface Config { + principal: Principal + verify(request: ConnectionTrustRequest): boolean +} + +export function apply(ctx: Context, config: Config): void { + const peer = ctx.connection.createPeer({ principal: config.principal }) + ctx.connection.authentication.register({ + authenticate(request) { + return config.verify(request) ? peer : undefined + }, + }) +} +``` + +`createPeer` 将 Peer 归入调用插件的作用域,`register` 将注册归入相同调用方作用域。共享身份的 Provider 像示例一样持有一个 Peer;按会话区分的 Provider 则持有自己的凭据到 Peer 记录,并返回对应的已有 Peer。Host 在创建时固定 `principal` 和可选 `interactions`,两者都不是客户端自行声明的授权信息。 + +`register` 返回异步 disposer,调用时同步撤销记录。认证读取注册顺序快照,跳过验证过程中撤销的记录,并在采用结果前复核 Peer 与请求。新注册参与后续请求。`authenticate` 返回首个存活 Peer、普通拒绝的401,或存在验证故障且无人成功时的503。来源拒绝仍是 Connection 单独作出的403决策。[实现](../../../../packages/client/connection/src/authentication.ts)包含这些生命周期检查。 + +### 声明路由准入并使用选定的 Peer + +`register`、`registerFallback` 与 `registerUpgrade` 接受 `auth: 'anonymous' | 'required' | 'deny'` 或同步选择器,默认值为 `required`。WebServer 先匹配路由、应用策略,再取得 Connection 的来源与凭据决策,并把选定 Peer 交给 handler。`deny` 不调用认证即拒绝;没有准入监听者时,`required` 返回503,`anonymous` 允许访问。 + +下面的示例注册普通业务 handler。Host 提供 `Config.upgrade`,即业务已有的协议实现,并非另一个框架操作。HTTP 中的断言对应此路由的 `required` 策略;公共 handler 类型同时支持没有 Peer 的匿名路由。 + +```ts +import type { Context } from '@deepseek-ai/cordis' +import type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' + +export const name = 'example-protected-routes' +export const inject = ['webServer'] + +export interface Config { + upgrade: WebUpgradeRoute['handler'] +} + +export function apply(ctx: Context, config: Config): void { + ctx.effect(() => ctx.webServer.register({ + kind: 'exact', + path: '/identity', + auth: 'required', + handler(_req, res, peer) { + res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }) + res.end(peer!.id) + }, + })) + ctx.effect(() => ctx.webServer.registerUpgrade({ + path: '/example/socket', + auth: 'required', + handler: config.upgrade, + })) +} +``` + +HTTP handler 接收 `(req, res, peer?)`,upgrade handler 接收 `(req, socket, head, peer?)`,resource 保留 `resource(request, peer?)`。业务 handler 不再遍历 Provider。Gateway 之外的直接管理路由(包括 Inspector 和 open-in-app)在访问 Host 资源前要求 owner Peer。可信进程内 `readResource(request, peer)` 保留显式 Peer,不执行网络来源或凭据检查,但仍遵守 `deny`。准入拒绝响应携带 `Cache-Control: no-store`。 + +### 使用有作用域的 WebServer 事件 + +每个 WebServer 事件都以对应 WebServer 为 Cordis thisArg。请求分发使用该服务实例,WebApp 入口收集传入 `ctx.webServer`。普通监听器匹配该 subject 的 `webServer` isolation,包括已有的 index 注入事件。`{ global: true }` 明确接收同一应用中跨服务隔离的事件。Peer 数据不选择事件监听器。[WebServer 参考](../../../../packages/host/webserver/README.zh.md)定义自定义载体的要求。 + +| 事件 | 模式 | 最终接线 | +|---|---|---| +| `webserver/request` | waterfall | 在路由选择前执行;Token 处理根 Token query 交换,账号插件处理经过校验的 OAuth 回调 | +| `webserver/authorize` | bail | 判断已匹配路由的来源与凭据准入,采用首个决策 | +| `webserver/upgrade` | waterfall | 在准入后、协议 handler 前执行,携带已选定的 Peer | +| `webserver/index-inject` | emit | 在服务器隔离范围内,为传入 Peer 收集页面或 Worker 启动数据 | +| `webserver/entry-url` | emit | 在服务器隔离范围内,为传入基地址收集完整入口 URL | + +Waterfall 监听器处理请求时拥有响应或 Socket,否则等待 `next()`。异常由载体容纳,并结束对应响应或 Socket。为支持登录协议,不会对所有匿名路由关闭来源策略。 + +账号插件在通用准入前注册临时回调监听器。它匹配发起登录时 redirect URI 的 authority 和精确路径,再保留 GET、单值 state/code、常量时间 state 比较、活动尝试检查、有效期、取消和 S256 PKCE。因此合法跨站浏览器返回可以完成,而不绕过这些校验,也不放宽无关匿名路由。监听器随尝试结束而移除,不导入 WebServer 实体辅助函数。 + +### Socket 策略归凭据签发产品 + +Token 监听器位于 `/connect` 路由旁,仅处理 `/api/remote.mux`。它按映射表对象身份识别自己的 API Peer,以409拒绝第二条 mux Socket,并在等待 Peer 和 Socket 清理前同步移除凭据。关闭 Inspector CDP Socket 不会认领或撤销该 API 会话。其他 Provider 保留各自生命周期策略;Gateway 只以传入的 Peer 执行协议升级。 + +Upgrade 为该连接固定 Peer,后续 HTTP 请求重新认证。Token 的浏览器共享 Peer 不随单条 Socket 关闭而结束,API Peer 则遵循已有 mux 生命周期。已经准入的一元调用保留自身取消作用域。[mux 回归](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts)和 [API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)覆盖这个区别。 + +### WebApp 发布完整入口 URL + +WebApp 保留 `publicUrl`、`printUrl` 和 `openBrowser`,两个输出开关默认均为 true。Loader 装配结束并完成启动审计后,它发出 `webserver/entry-url`,传入自己的 WebServer subject、普通基地址和初始为空的 `WebEntryUrl[]`。每条入口包含 `label`、完整 `url` 和布尔值 `open`。 + +Token 不读取 WebApp 服务,只贡献带签名的 `dsh web` URL。没有用户入口的 Provider 不贡献条目,其他产品可以贡献自己的 label 和完整 URL。启用打印时,WebApp 逐行输出 `label: url`;启用浏览器打开且不在 SSH 下时,只打开首个 `open: true` 条目。空列表不产生输出或浏览器打开。即使接线未公开原始 Token getter,进程凭据仍是敏感信息。 + +Desktop 父进程为每个 Host 进程持有新私有凭据,并在 ready 前交付。Desktop Provider 创建 Peer,通过相同认证服务注册验证。Electron 使用本地组装的 `authenticationCookie`;runtime smoke 等父进程消费者不使用普通 ready URL 尝试 Token 交换。Renderer 启动数据和 wire ready 消息不含私有凭据。 + +## Testing + +| 受影响行为 | 原行为 | 最终行为与覆盖 | +|---|---|---| +| Provider 注册 | 只有内置 BrowserAuth 提供网络身份 | 有序独立验证器选择一个存活 Peer;[认证测试](../../../../packages/client/connection/tests/authentication.host.spec.ts)覆盖作用域卸载、验证故障和取消 | +| HTTP 与 upgrade 接入 | 消费者调用 Connection 准入 | 路由 auth 一次提供 Peer;真实 [Provider 传输测试](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts)覆盖两种载体 | +| 服务器隔离 | 路由表按实例持有,index 注入覆盖 root | 五个事件均使用 WebServer subject;[服务器](../../../../packages/host/webserver/tests/event-isolation.host.spec.ts)和[应用](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts)测试覆盖普通/global 监听器及保留的外部 Host | +| 浏览器 OAuth 返回 | 回调校验 state 与 PKCE | 有作用域的前置回调保留校验,并接受真实跨站导航;[账号测试](../../../../packages/credentials/deepseek-account/tests/account.spec.ts)保留错误 Host 和 SSH 转发覆盖,[Chromium](../../../../apps/web/tests/account-login.e2e.ts)断言实际 Fetch Metadata header | +| 启动输出 | WebApp 打印/打开一个 Connection 生成的登录 URL | [启动测试](../../../../packages/bundle/web-app/tests/startup.host.spec.ts)覆盖按序入口、首个可打开项、空列表、就绪和 SSH 抑制 | +| Desktop runtime 消费者 | 以带 Token 的 ready URL 交换 Cookie | [Runtime smoke 测试](../../../../apps/desktop/tests/smoke-runtime.spec.ts)在 HTTP 探针中使用私有 Cookie;[产物 Remote 测试](../../../../packages/api/remotes/tests/built-lib.e2e.ts)收集当前 Provider 入口,并传递准入 Peer | + +## Alternatives considered + +**在 Connection 上保留逐请求认证包装。** 独立注册的 Service 直接表达所有权和必需注入,不在每次消费者读取认证时分配 facade。 + +**增加另一张路由表或请求上下文容器。** 现有 WebServer 注册已拥有分发,Peer 就是下游消费的身份。路由策略和末尾 Peer 参数保留这些 owner。 + +**给每个请求增加 WebServer 字段。** Cordis 已支持服务 subject 与隔离过滤。采用该机制也能限制页面注入和入口收集的作用域,而不增加 payload 字段。 + +**让 Token 持有 WebApp 地址服务或浏览器 opener。** 这会反向依赖组装它的 bundle。WebApp 拥有发布时机和动作,Provider 通过共同事件贡献完整入口。 + +## Consequences + +凭据实现不需要改变 Gateway,但自定义载体必须以自己的 WebServer subject 发事件,并把准入 Peer 传给协议 handler。消费嵌套认证服务的插件在注入中声明 `connection.authentication`。显式全局事件监听器仍负责判断跨服务器实例共享数据是否合适。 + +撤销 Provider 注册和释放其 Peer 是不同操作。共享一个 Peer 的产品也共享其终止范围;使用独立凭据的产品持有自己的 Peer 记录和撤销策略。此接线不增加通用 Socket 策略或另一层认证权限等级。 + +[Provider 决策](2026-11-07-browser-authentication-providers.zh.md)拥有协议兼容性和部署后果。[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md)拥有手动配置迁移和载体更新说明;本记录描述已经实现的接线,而非未来 Remote 产品。 diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.i18n.yaml new file mode 100644 index 0000000000..fdfa8772ab --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-07-browser-authentication-providers.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.md +/agent-note-peer-based-authentication-providers: + en: dc115ba91f14e5b5 + zh: f1a833e5cc9b5de4 +/agent-note-peer-based-authentication-providers/problem: + en: f4a95ed5454d059d + zh: 20c3ffeac8ec2b6f +/agent-note-peer-based-authentication-providers/decision: + en: a15c7c13f167e5ac + zh: a15c7c13f167e5ac +/agent-note-peer-based-authentication-providers/decision/independent-authentication-and-equal-providers: + en: 3bc63d9822e90803 + zh: 0763d1106b8e36ea +/agent-note-peer-based-authentication-providers/decision/identity-authorization-and-lifetime-remain-separate: + en: ec74d7af014cd9e5 + zh: 04495d74691073a8 +/agent-note-peer-based-authentication-providers/decision/effects-on-http-events-and-startup: + en: 6b2742912d440682 + zh: ec3c7fd3993f1367 +/agent-note-peer-based-authentication-providers/decision/preserved-protocols-and-explicit-limits: + en: d5fb7d9f70ccb9a8 + zh: 5e78c868370deffd +/agent-note-peer-based-authentication-providers/testing: + en: 1ae7c77c7388883a + zh: eb2145ec79691f81 +/agent-note-peer-based-authentication-providers/alternatives-considered: + en: aa5de8e27414700b + zh: 35604d226908afc2 +/agent-note-peer-based-authentication-providers/consequences: + en: 61065aecfda88a3c + zh: 518f3f76ef167a31 diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.md b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.md new file mode 100644 index 0000000000..559dbb24e1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.md @@ -0,0 +1,85 @@ +# Agent Note: Peer-based authentication Providers + +Status: implemented + +English | [中文](2026-11-07-browser-authentication-providers.zh.md) + +## Problem + +The Host serves tool-capable operations, so a reachable address cannot establish caller identity. Browser login, Desktop access, and remote invitation or pairing flows need different credential implementations without giving each transport a different authorization model. + +Before this separation, WebServer owned HTTP and upgrade listeners and their per-instance route tables. Connection constructed the built-in BrowserAuth, checked request sources, verified browser and API Cookies, and managed the existing API Peer attachment. Route owners called Connection admission methods themselves. WebApp asked Connection to add the launch token to its advertised address, then printed or opened that URL. The old `webserver/index-inject` event broadcast within the Cordis root independently of the route tables. + +That arrangement made the default Token implementation part of the generic connection service. Another authentication product needed the same Peer result but could not supply its own verifier through a common registration interface. + +## Decision + +### Independent authentication and equal Providers + +ConnectionAuthentication is an independent Service in the Connection package, registered as `connection.authentication` and accessed through `ctx.connection.authentication`. It owns credential-verifier registration and selection. Connection retains request-source policy, Peer creation, and RPC/Fetch operations; WebServer enforces route admission and supplies the selected Peer to handlers. Gateway and RemoteAccess authorize operations using that Peer. + +An AuthenticationProvider synchronously returns an existing live Peer or `undefined`. ConnectionAuthentication tries Providers in actual registration order and accepts the first live result. An ordinary refusal or ended Peer permits a later Provider to succeed; an exception also permits later success. With no success, ordinary refusal returns401 and a verification failure returns503. Request cancellation stops admission. This is one selection pass, not a priority or privilege ranking between credential kinds. + +| Access method | Credential implementation | Peer ownership | +|---|---|---| +| Web and API Token | The Token plugin verifies its process-token exchanges and signed Cookies | Browser v1 Cookies share a plugin-owned Peer; `/connect` v2 Cookies identify an existing independent API Peer | +| Desktop | The Desktop Provider verifies the private credential delivered over parent–Host IPC | One Peer belongs to the Provider for that owned Host process | +| Remote | The same Provider interface accepts a product's invitation or pairing verifier | The product determines its own principal, credentials, and Peer lifetime; the Remote product itself is not implemented | + +The shared authentication extension is complete independently of the future Remote product. The [integration note](2026-11-07-browser-authentication-development.md) gives a typed Provider example and the route and event usage. + +### Identity, authorization, and lifetime remain separate + +The Host fixes `peer.principal` when creating the Peer; the client cannot choose it through a request field. Authentication establishes that identity, not permission for every operation. RemoteAccess continues to evaluate business permissions, and `peer.interactions` continues to control forwarded-event participation rather than an authentication level. + +Each registering plugin owns its registration, and each Peer creator owns the Peer scope. Credential withdrawal prevents later authentication; ending a Peer also ends its Peer-scoped communication. Already-admitted unary requests retain their request-level cancellation semantics. Asynchronous Provider preparation can affect actual registration order, so deployments cannot infer a separate priority from credential names. + +### Effects on HTTP, events, and startup + +WebServer route registrations declare `anonymous`, `required`, or `deny`; omission means `required`. Protected handlers receive the Peer selected by centralized admission rather than calling each verifier. Anonymous routes skip credentials but still undergo the active Connection source policy. Trusted in-process resource reads retain their explicit Peer and still honor `deny`. + +All five `webserver/*` events carry the corresponding WebServer as their Cordis dispatch subject. Ordinary listeners follow `webServer` service isolation; explicit `global: true` listeners opt out. This applies to request admission, upgrade middleware, the existing page-injection event, and entry-URL collection. Service isolation is a composition mechanism, not a sandbox for same-process plugins. + +The Token plugin owns root Token exchange and `/connect` issuance. Its upgrade middleware claims its API Peers only at `/api/remote.mux`, preserving one Socket per API Peer, duplicate409, and synchronous credential revocation before asynchronous cleanup. Inspector and other upgrade routes do not claim that lifecycle. WebApp owns readiness, `printUrl` and `openBrowser` (both default true), SSH suppression, and publication: it collects complete entries, prints them in order, and opens only the first eligible one. No entries means no output or opening. + +### Preserved protocols and explicit limits + +The [browser Token protocol](2026-08-24-browser-token-authentication.md) retains the process token, signed authority-bound Cookie, persistent `client-connection/browser-session` signing record, expiry checks, and listener-controlled `Secure` attribute. The [API connect decision](2026-10-09-operator-scoped-connect-handshake.md) retains independent API Peers, HTTP before Socket attachment, interaction participation, and mux cleanup. A valid v2 Cookie can also authenticate a protected page; page access does not create another credential tier. + +Desktop uses its private credential directly rather than exchanging a Token URL. The renderer receives ordinary addresses and startup data, not the private credential; the wire `ready` message contains no secret. Desktop can also offer Token login and its printed entry URL. Normal shutdown or parent disconnection while awaiting the Desktop credential ends startup without a fatal authentication error; invalid or repeated credentials remain failures. + +Token activation failure may leave the application running without that Provider; it never grants unauthenticated access to a protected route. Token owns `cookieMaxAgeDays`, default30 days. Operators manually move an old Connection setting to Token: the old location is not migrated or rejected and does not affect the Token lifetime. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md) owns that migration. + +## Testing + +The before/after comparison uses the original built-in-authentication design as its baseline. + +| Affected behavior | Before | Final behavior | +|---|---|---| +| Credential selection | Connection directly used BrowserAuth | Token and Desktop use the same ordered Provider service; another Provider can succeed after refusal or failure | +| Protected HTTP and upgrades | Route owners invoked Connection admission | Route policy centralizes admission and passes one selected Peer to the handler | +| Credential persistence | Browser Cookies survived restart; API Peers did not | The same Token formats, authority checks, restart behavior, and API retention rules remain | +| API lifecycle Socket | Gateway attachment owned one API Peer | Token's mux middleware retains duplicate409 and close-time revocation without claiming other upgrades | +| Event scope | Routes were instance-owned; page injection broadcast | WebServer subjects filter all five events by service isolation, with an explicit global escape | +| Browser startup | WebApp printed/opened one Connection-produced URL | WebApp keeps its defaults and readiness rules while publishing ordered Provider contributions | +| Desktop startup | Desktop exchanged the launch URL for a Cookie | Desktop uses private IPC credentials; normal early shutdown is acknowledged | + +The [Connection tests](../../../../packages/client/connection/tests/authentication.host.spec.ts), [real transport composition](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts), [mux lifecycle tests](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts), and [WebApp isolation tests](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts) cover these behaviors. The integration note covers callback and custom-carrier verification. + +## Alternatives considered + +**Keep Token-specific operations inside Connection.** This couples every authentication product to the default credential implementation. A generic credential registry returns the Peer already consumed by the transport and authorization layers. + +**Return a boolean or a binding identifier and resolve the Peer later.** A boolean leaves identity unresolved; a binding identifier adds another mapping and owner. Providers already own their Peers, so successful verification returns that object directly. + +**Authenticate separately in each HTTP and upgrade handler.** Repeated checks can disagree and omit new routes. Route policy and centralized admission make the requirement explicit while leaving endpoint-specific tickets and input validation with the endpoint. + +**Put product Socket policy in a Peer subtype or binding API.** The single-Socket rule belongs to `/connect`'s mux session, not every Peer. Business-owned upgrade middleware preserves that rule without a generic Peer policy flag or a Gateway dependency on Token. + +## Consequences + +Adding a credential implementation does not change Gateway dispatch or the existing Peer protocol. Provider initialization, credential storage, login interaction, and session lifetime remain product responsibilities. Default Token and Desktop use the same interface that a Remote product can adopt, without claiming that invitation or approval UI already exists. + +Central route admission changes the default for previously unclassified routes to `required`; public endpoints need explicit policy. Instance-scoped events prevent an isolated WebServer from inheriting another server's ordinary listeners, but a deliberately global listener remains application-wide. A credential-bearing entry URL is sensitive output even though no raw Token getter is exposed. + +This decision partially extends the implementation ownership in the browser Token, API connect, and [request-source policy](2026-07-28-api-browser-trust-boundary.md) records. Those records remain active for their credential, lifecycle, and security rationale; none is fully superseded or archived. diff --git a/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.zh.md b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.zh.md new file mode 100644 index 0000000000..127d0df4b8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-07-browser-authentication-providers.zh.md @@ -0,0 +1,85 @@ +# Agent Note: 基于 Peer 的认证 Provider + +Status: implemented + +[English](2026-11-07-browser-authentication-providers.md) | 中文 + +## Problem + +Host 提供具备工具执行能力的操作,因此可达地址不能建立调用方身份。浏览器登录、Desktop 访问和远程邀请或配对需要不同的凭据实现,但不应为每种传输建立不同的授权模型。 + +拆分前,WebServer 拥有 HTTP 与 upgrade 监听器及各实例的路由表。Connection 构造内置 BrowserAuth,检查请求来源、验证浏览器与 API Cookie,并管理已有的 API Peer 关联。路由 owner 自行调用 Connection 准入方法。WebApp 请求 Connection 为公告地址附加启动 Token,再打印或打开该 URL。旧 `webserver/index-inject` 事件在 Cordis root 内广播,与路由表的实例范围无关。 + +这种关系把默认 Token 实现放进了通用连接服务。其他认证产品同样需要返回 Peer,却没有公共注册接口可以接入自己的验证器。 + +## Decision + +### 独立认证与平级 Provider + +ConnectionAuthentication 是 Connection 包内的独立 Service,注册名为 `connection.authentication`,通过 `ctx.connection.authentication` 访问。它拥有凭据验证器注册与选择。Connection 保留请求来源策略、Peer 创建和 RPC/Fetch 操作;WebServer 执行路由准入并向 handler 传递选定的 Peer。Gateway 与 RemoteAccess 使用该 Peer 授权操作。 + +AuthenticationProvider 同步返回已存在且存活的 Peer 或 `undefined`。ConnectionAuthentication 按实际注册顺序尝试 Provider,采用首个存活结果。普通拒绝或已结束 Peer 允许后续 Provider 成功;异常也不阻止后续成功。无人成功时,普通拒绝返回401,存在验证故障则返回503。请求取消终止准入。这是一次选择过程,不是凭据种类之间的优先级或权限等级。 + +| 访问方式 | 凭据实现 | Peer 所有权 | +|---|---|---| +| Web 与 API Token | Token 插件验证进程 Token 交换和签名 Cookie | 浏览器 v1 Cookie 共享插件持有的 Peer;`/connect` v2 Cookie 标识已有的独立 API Peer | +| Desktop | Desktop Provider 验证通过父进程—Host IPC 交付的私有凭据 | 一个 Peer 属于该自有 Host 进程的 Provider | +| Remote | 同一个 Provider 接口可接收产品自己的邀请或配对验证器 | 产品决定自己的 principal、凭据和 Peer 生命周期;Remote 产品本身尚未实现 | + +公共认证扩展能力已经完成,不取决于未来 Remote 产品的完成状态。[接入说明](2026-11-07-browser-authentication-development.zh.md)提供带类型的 Provider 示例及路由、事件用法。 + +### 身份、授权与生命周期相互独立 + +Host 在创建 Peer 时固定 `peer.principal`;客户端不能通过请求字段选择它。认证建立该身份,不代表允许所有操作。RemoteAccess 继续判断业务权限,`peer.interactions` 继续控制转发事件参与方式,而不是认证等级。 + +注册由调用插件拥有,Peer 作用域由创建者拥有。凭据撤销阻止后续认证,结束 Peer 也结束其作用域内的通信。已经准入的一元请求保留请求级取消语义。Provider 异步准备可能影响实际注册顺序,因此部署不能从凭据名称推导另一套优先级。 + +### HTTP、事件与启动的变化 + +WebServer 路由注册声明 `anonymous`、`required` 或 `deny`,省略时为 `required`。受保护的 handler 接收集中准入选定的 Peer,不再自行调用各个验证器。匿名路由免凭据,但仍经过活动 Connection 的来源策略。可信进程内资源读取保留显式 Peer,并继续遵守 `deny`。 + +五个 `webserver/*` 事件均以对应 WebServer 为 Cordis 分发 subject。普通监听器遵循 `webServer` 服务隔离;显式 `global: true` 监听器跳过该过滤。请求准入、upgrade 中间件、已有页面注入事件和入口 URL 收集均采用该规则。服务隔离是组合机制,不是同进程插件的安全沙箱。 + +Token 插件拥有根 Token 交换和 `/connect` 签发。它的 upgrade 中间件仅在 `/api/remote.mux` 上认领自己的 API Peer,保留每个 API Peer 一个 Socket、重复409,以及在异步清理前同步撤销凭据的行为。Inspector 与其他 upgrade 路由不认领该生命周期。WebApp 拥有就绪、`printUrl` 与 `openBrowser`(两者默认 true)、SSH 抑制和发布:收集完整入口,按序打印,只打开首个可自动打开的入口。没有入口则不输出、不打开。 + +### 保留的协议与明确限制 + +[浏览器 Token 协议](2026-08-24-browser-token-authentication.zh.md)保留进程 Token、绑定 authority 的签名 Cookie、持久 `client-connection/browser-session` 签名记录、有效期检查和由监听协议决定的 `Secure` 属性。[API connect 决策](2026-10-09-operator-scoped-connect-handshake.zh.md)保留独立 API Peer、HTTP 先于 Socket 关联、交互参与方式和 mux 清理。有效 v2 Cookie 也可认证受保护页面;页面访问不建立另一层凭据等级。 + +Desktop 直接使用私有凭据,不交换 Token URL。Renderer 接收普通地址与启动数据,不接收私有凭据;wire `ready` 消息不含秘密。Desktop 也可提供 Token 登录及其打印入口 URL。等待 Desktop 凭据时的正常 shutdown 或父通道断连不会导致致命认证错误;非法或重复凭据仍然失败。 + +Token 激活失败允许应用缺少该 Provider 继续运行,但不授予受保护路由的未认证访问。Token 拥有 `cookieMaxAgeDays`,默认为30天。用户手动将旧 Connection 设置移到 Token:旧位置既不会自动迁移,也不会被拒绝,并且不影响 Token 有效期。[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md)拥有迁移说明。 + +## Testing + +前后对比以原内置认证设计为基线。 + +| 受影响行为 | 原行为 | 最终行为 | +|---|---|---| +| 凭据选择 | Connection 直接使用 BrowserAuth | Token 与 Desktop 使用同一个有序 Provider 服务;前项拒绝或故障后其他 Provider 仍可成功 | +| 受保护 HTTP 与 upgrade | 路由 owner 调用 Connection 准入 | 路由策略集中执行准入,并向 handler 传递一个选定的 Peer | +| 凭据持久化 | 浏览器 Cookie 可跨重启,API Peer 不可 | Token 格式、authority 检查、重启行为和 API 保留规则保持 | +| API 生命周期 Socket | Gateway 关联拥有一个 API Peer | Token 的 mux 中间件保留重复409和关闭时撤销,不认领其他 upgrade | +| 事件范围 | 路由按实例持有,页面注入广播 | WebServer subject 按服务隔离过滤五个事件,同时保留显式 global 出口 | +| 浏览器启动 | WebApp 打印/打开一个由 Connection 生成的 URL | WebApp 保留默认值与就绪规则,发布 Provider 按序贡献的入口 | +| Desktop 启动 | Desktop 交换启动 URL 取得 Cookie | Desktop 使用私有 IPC 凭据,并确认正常的早期关闭 | + +[Connection 测试](../../../../packages/client/connection/tests/authentication.host.spec.ts)、[真实传输组合](../../../../packages/api/gateway/tests/authentication-provider.host.spec.ts)、[mux 生命周期测试](../../../../packages/api/gateway/tests/operator-connect.host.spec.ts)与 [WebApp 隔离测试](../../../../packages/bundle/web-app/tests/event-isolation.host.spec.ts)覆盖这些行为。接入说明补充回调与自定义载体的验证。 + +## Alternatives considered + +**将 Token 专属操作保留在 Connection 内。** 这会让每个认证产品依赖默认凭据实现。通用凭据注册表直接返回传输与授权层已经使用的 Peer。 + +**返回布尔值或绑定标识,再解析 Peer。** 布尔值无法确定身份,绑定标识则增加映射与 owner。Provider 已经持有自己的 Peer,验证成功直接返回该对象。 + +**每个 HTTP 与 upgrade handler 分别认证。** 重复检查可能不一致,也可能漏掉新路由。路由策略与集中准入明确表达要求,端点专属票据和输入校验仍由端点负责。 + +**将业务 Socket 策略放入 Peer 子类或绑定 API。** 单 Socket 规则属于 `/connect` 的 mux 会话,不属于所有 Peer。业务拥有的 upgrade 中间件保留该规则,不需要通用 Peer 策略标志,也不让 Gateway 依赖 Token。 + +## Consequences + +新增凭据实现不改变 Gateway 分发或已有 Peer 协议。Provider 初始化、凭据存储、登录交互和会话生命周期仍由产品负责。默认 Token 与 Desktop 使用未来 Remote 产品也能采用的同一接口,但不声称邀请或审批 UI 已经存在。 + +集中路由准入把此前未分类路由的默认策略设为 `required`,公开端点需要显式声明策略。按实例作用域分发的事件阻止隔离 WebServer 接收另一台服务器的普通监听器,但显式全局监听器仍覆盖应用。即使没有公开原始 Token getter,含凭据的入口 URL 仍属于敏感输出。 + +本决策只部分扩展浏览器 Token、API connect 与[请求来源策略](2026-07-28-api-browser-trust-boundary.zh.md)记录中的实现归属。原记录继续保留凭据、生命周期和安全规则的独立理由,没有任何一份被完全取代或归档。 diff --git a/apps/cli/tests/desktop-host.e2e.ts b/apps/cli/tests/desktop-host.e2e.ts index a0e0ab9c92..7ea30e1fad 100644 --- a/apps/cli/tests/desktop-host.e2e.ts +++ b/apps/cli/tests/desktop-host.e2e.ts @@ -1,14 +1,23 @@ -/** Built Desktop Host lifecycle with Electron disconnecting before profile startup settles. */ +/** Built Desktop Host credential receipt and shutdown before profile startup settles. */ import { fork } from 'node:child_process' -import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { randomBytes } from 'node:crypto' +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { delimiter, dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { finished } from 'node:stream/promises' import { expect, it, onTestFinished } from 'vitest' -it.each([false, true])('settles startup after parent IPC disconnect (boot failure: %s)', async (fail) => { +it.each([ + { event: 'disconnect', phase: 'credentials', fail: false }, + { event: 'shutdown', phase: 'credentials', fail: false }, + { event: 'invalid-credential', phase: 'credentials', fail: true }, + { event: 'disconnect', phase: 'startup', fail: false }, + { event: 'disconnect', phase: 'startup', fail: true }, + { event: 'shutdown', phase: 'startup', fail: false }, + { event: 'shutdown', phase: 'startup', fail: true }, +] as const)('settles $event while waiting for $phase (failure: $fail)', async ({ event, phase, fail }) => { const root = mkdtempSync(join(tmpdir(), 'desktop-disconnect-')) const modules = join(root, 'node_modules', '@deepseek-ai') const hostDirectory = fileURLToPath(new URL('../../desktop-host/', import.meta.url)) @@ -23,8 +32,12 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur writeFileSync(join(root, 'package.json'), '{"type":"module"}') writeFileSync(join(modules, 'dsh-app-boot', 'package.json'), '{"type":"module","exports":"./index.js"}') writeFileSync(join(modules, 'dsh-app-boot', 'index.js'), ` + import { writeFileSync } from 'node:fs'; export class StartupError extends Error {} - export const loadProfileDirectory = () => ({ skippedBundles: [] }); + export const loadProfileDirectory = () => { + writeFileSync(${JSON.stringify(join(root, 'profile-loaded'))}, 'loaded'); + return { skippedBundles: [] }; + }; export const reportSkippedBundles = () => {}; export const loadLayeredEnv = () => ({}); `) @@ -33,12 +46,19 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur import { writeFileSync } from 'node:fs'; export function runProfile(options) { process.send({ type: 'booting', packageManager: options.packageManager }); - return new Promise((resolve, reject) => process.once('disconnect', () => { - if (${String(fail)}) { reject(new Error('fixture boot failure')); return; } - resolve({ ctx: { plugin: async () => {}, effect: () => {}, on: () => {}, inject: () => {}, - connection: { authenticatedUrl: value => value }, webServer: { port: 19387 } }, - shutdown: { shutdown: async () => writeFileSync(${JSON.stringify(join(root, 'stopped'))}, 'stopped') } }); - })); + return new Promise((resolve, reject) => { + const settle = () => { + process.off('disconnect', settle); + process.off('message', onMessage); + if (${String(fail)}) { reject(new Error('fixture boot failure')); return; } + resolve({ ctx: { plugin: async () => {}, effect: () => {}, on: () => {}, inject: () => {}, + connection: { authenticatedUrl: value => value }, webServer: { port: 19387 } }, + shutdown: { shutdown: async () => writeFileSync(${JSON.stringify(join(root, 'stopped'))}, 'stopped') } }); + }; + const onMessage = message => { if (message.type === 'shutdown') settle(); }; + process.once('disconnect', settle); + process.on('message', onMessage); + }); } `) const entry = join(root, 'index.js') @@ -50,6 +70,8 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur child.stderr!.setEncoding('utf8').on('data', (chunk: string) => { stderr += chunk }) const exited = new Promise(resolve => child.once('exit', resolve)) const drained = finished(child.stderr!, { cleanup: true }) + const messages: unknown[] = [] + child.on('message', (message) => { messages.push(message) }) onTestFinished(async () => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') await Promise.all([exited, drained]) @@ -58,28 +80,56 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur try { const boot = await new Promise<{ packageManager: { command: string; args: string[]; env: Record } - }>((resolve, reject) => { + } | undefined>((resolve, reject) => { child.on('message', (message) => { + if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'starting') { + if (phase === 'credentials') { resolve(undefined); return } + child.send({ type: 'desktop-auth', secret: randomBytes(32).toString('base64url') }, (error) => { + if (error !== null) reject(error) + }) + } if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'booting' && 'packageManager' in message) { resolve(message as { packageManager: { command: string; args: string[]; env: Record } }) } }) child.once('error', reject) - child.once('exit', (code) => { reject(new Error(`Host exited before booting: ${String(code)} ${stderr}`)) }) + child.once('exit', (code) => { reject(new Error(`Host exited before ${phase}: ${String(code)} ${stderr}`)) }) + }) + if (phase === 'startup') { + expect(boot?.packageManager.command).toBe(process.execPath) + expect(boot?.packageManager.args).toEqual(['--expose-internals', pnpm]) + expect(boot?.packageManager.env.ELECTRON_RUN_AS_NODE).toBe('1') + expect(boot?.packageManager.env.PATH).toBe(`${nodeBin}${delimiter}${process.env.PATH ?? ''}`) + } + if (event === 'disconnect') child.disconnect() + else await new Promise((resolve, reject) => { + child.send(event === 'shutdown' ? { type: 'shutdown' } : { type: 'desktop-auth', secret: 'bad-secret' }, (error) => { + if (error === null) resolve() + else reject(error) + }) }) - expect(boot.packageManager.command).toBe(process.execPath) - expect(boot.packageManager.args).toEqual(['--expose-internals', pnpm]) - expect(boot.packageManager.env.ELECTRON_RUN_AS_NODE).toBe('1') - expect(boot.packageManager.env.PATH).toBe(`${nodeBin}${delimiter}${process.env.PATH ?? ''}`) - child.disconnect() const exitCode = await exited await drained expect(child.signalCode).toBeNull() expect(exitCode, stderr).toBe(fail ? 1 : 0) expect(stderr).not.toContain('ERR_IPC_CHANNEL_CLOSED') expect(stderr).not.toContain('Unhandled') - if (fail) expect(stderr).toContain('fixture boot failure') - else expect(readFileSync(join(root, 'stopped'), 'utf8')).toBe('stopped') + expect(messages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'ready' })])) + if (event === 'shutdown' && !fail) { + expect(messages.filter(message => typeof message === 'object' && message !== null && 'type' in message + && message.type === 'shutdown-complete')).toHaveLength(1) + } + if (fail) { + expect(stderr).toContain(event === 'invalid-credential' ? 'Desktop authentication message is invalid' : 'fixture boot failure') + } else { + expect(stderr).toBe('') + expect(messages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'fatal' })])) + } + if (phase === 'credentials') { + expect(existsSync(join(root, 'profile-loaded'))).toBe(false) + expect(existsSync(join(root, 'stopped'))).toBe(false) + expect(messages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'booting' })])) + } else if (!fail) expect(readFileSync(join(root, 'stopped'), 'utf8')).toBe('stopped') } finally { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') await Promise.all([exited, drained]) diff --git a/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts index 64ab162454..e12b047b5c 100644 --- a/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts @@ -64,13 +64,15 @@ function fixture() { // A recovery URL is a readiness signal; sibling HMR work must settle first. ' void scope.get("loader").await().then(() => {', ' if (disposed || !scope.get("webServer") || !scope.get("connection")) return', - ' writeFileSync(config.url, scope.connection.authenticatedUrl(`http://127.0.0.1:${scope.webServer.port}`))', + ' writeFileSync(config.url, `http://127.0.0.1:${scope.webServer.port}`)', ' })', ' })', '}', '', ].join('\n')) - const observer = { id: 'matrix-log-observer', name: pathToFileURL(observerPath).href, config: { path: diagnostics, url: serverUrl, states } } + const observer = { id: 'matrix-log-observer', name: pathToFileURL(observerPath).href, config: { + path: diagnostics, url: serverUrl, states, + } } const plugin = join(root, 'probe.mjs') writeFileSync(plugin, [ "import { appendFileSync, existsSync } from 'node:fs'", @@ -134,8 +136,11 @@ function start(f: ReturnType, extra: string[] = [], nodeArgs: st } async function serves(currentServer = false) { await wait(() => /dsh web: http:\/\//u.test(stdout)) - const url = currentServer ? readFileSync(f.serverUrl, 'utf8') : /dsh web: (http:\/\/[^\s]+)/u.exec(stdout)?.[1] - if (!url) throw new Error('Missing Web URL') + const publishedUrl = /dsh web: (http:\/\/[^\s]+)/u.exec(stdout)?.[1] + if (!publishedUrl) throw new Error('Missing Web URL') + const url = new URL(currentServer ? readFileSync(f.serverUrl, 'utf8') : publishedUrl) + // The real token plugin publishes once per process; HMR can replace the listener. + url.search = new URL(publishedUrl).search const auth = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(10_000) }) const cookie = auth.headers.get('set-cookie')?.split(';', 1)[0] if (!cookie) throw new Error('Missing Web authentication cookie') diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index 20f70a7aa4..07943dc431 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -18,6 +18,7 @@ "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-host-authentication-desktop": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-schedule": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", @@ -25,6 +26,11 @@ "@deepseek-ai/dsh-plugin-manager": "workspace:*" }, "devDependencies": { + "ws": "^8.21.3", + "@types/ws": "^8.18.1", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@deepseek-ai/dsh-typert-registry": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", diff --git a/apps/desktop-host/src/authentication.ts b/apps/desktop-host/src/authentication.ts new file mode 100644 index 0000000000..09081f1cf2 --- /dev/null +++ b/apps/desktop-host/src/authentication.ts @@ -0,0 +1,70 @@ +/** Receive the Desktop startup credential over the private parent IPC channel. */ + +interface AuthenticationChannel { + readonly connected: boolean + on(event: 'message', listener: (message: unknown) => void): unknown + on(event: 'disconnect', listener: () => void): unknown + off(event: 'message', listener: (message: unknown) => void): unknown + off(event: 'disconnect', listener: () => void): unknown +} + +/** Normal parent termination before or after private credential delivery. */ +export class DesktopAuthenticationEnd extends Error { + constructor(readonly kind: 'shutdown' | 'disconnected') { + super(kind === 'shutdown' ? 'Desktop authentication cancelled by shutdown' : 'Desktop authentication channel disconnected') + this.name = 'DesktopAuthenticationEnd' + } +} + +/** One private credential receipt and the lifetime of its parent channel. */ +export interface DesktopSecretReceipt { + readonly secret: Promise + readonly signal: AbortSignal + /** Remove private IPC listeners and end any pending receipt. */ + dispose(): void +} + +/** + * Install credential receipt before publishing the Host's starting message. + * @param channel - owned parent IPC connection. + * @returns one credential and a signal ended by disconnect, shutdown, invalid input, or duplicate delivery. + * Pending receipt rejects with DesktopAuthenticationEnd for normal parent termination; malformed or repeated credentials remain failures. + */ +export function receiveDesktopSecret(channel: AuthenticationChannel): DesktopSecretReceipt { + const delivered = Promise.withResolvers() + const lifetime = new AbortController() + let received = false + const detach = (): void => { + channel.off('message', onMessage) + channel.off('disconnect', onDisconnect) + } + const end = (error: Error): void => { + if (lifetime.signal.aborted) return + detach() + lifetime.abort(error) + delivered.reject(error) + } + const onDisconnect = (): void => { end(new DesktopAuthenticationEnd('disconnected')) } + const onMessage = (message: unknown): void => { + if (typeof message !== 'object' || message === null || !('type' in message)) return + if (message.type === 'shutdown') { end(new DesktopAuthenticationEnd('shutdown')); return } + if (message.type !== 'desktop-auth') return + if (received) { end(new Error('Desktop authentication credential already received')); return } + if (Array.isArray(message) || Object.keys(message).length !== 2 || !('secret' in message) || typeof message.secret !== 'string' + || !/^[A-Za-z0-9_-]{43}$/u.test(message.secret) + || Buffer.from(message.secret, 'base64url').toString('base64url') !== message.secret) { + end(new Error('Desktop authentication message is invalid')) + return + } + received = true + delivered.resolve(message.secret) + } + channel.on('message', onMessage) + channel.on('disconnect', onDisconnect) + if (!channel.connected) onDisconnect() + return { + secret: delivered.promise, + signal: lifetime.signal, + dispose() { end(new Error('Desktop authentication receiver disposed')) }, + } +} diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index 966e51a364..7664fb11d4 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -15,10 +15,29 @@ import { installDesktopUpdateTaskControl } from './update-tasks.ts' import { installDesktopQuitInspection } from './quit-inspection.ts' import { installPlatformSessionPublisher } from './platform-session.ts' import { installOperationDiagnostics } from './operation-diagnostics.ts' +import { DesktopAuthenticationEnd, receiveDesktopSecret } from './authentication.ts' +import * as DesktopAuthentication from '@deepseek-ai/dsh-host-authentication-desktop' async function main(): Promise { const runId = randomUUID() as PluginOperationRunId - if (process.connected) process.send?.({ type: 'starting', runId }, (error) => { if (error !== null) console.error(error) }) + const authentication = receiveDesktopSecret(process) + if (process.connected) process.send?.({ type: 'starting', runId }, (error) => { + if (error !== null) authentication.dispose() + }) + const send = (message: object): Promise => new Promise((resolve, reject) => { + if (!process.connected || process.send === undefined) { resolve(); return } + process.send(message, (error) => { if (error === null) resolve(); else reject(error) }) + }) + let secret: string + try { + secret = await authentication.secret + authentication.signal.throwIfAborted() + } catch (error) { + if (!(error instanceof DesktopAuthenticationEnd)) throw error + if (error.kind === 'shutdown') await send({ type: 'shutdown-complete' }) + if (process.connected) process.disconnect() + return + } const runtimeDir = process.argv[2] as string const projectDir = process.argv[3] as string // Set before the launch-environment snapshot and profile evaluation; empty means the payload sits beside the runtime directory. @@ -51,10 +70,6 @@ async function main(): Promise { updateTasks?: ReturnType quitInspection?: ReturnType } = {} - const send = (message: object): Promise => new Promise((resolve, reject) => { - if (!process.connected || process.send === undefined) { resolve(); return } - process.send(message, (error) => { if (error === null) resolve(); else reject(error) }) - }) const stop = (): Promise => stopping ??= (async () => { for (const abort of dragReads.values()) abort.abort() await Promise.allSettled(dragTasks) @@ -124,16 +139,33 @@ async function main(): Promise { } })().catch((error: unknown) => { console.error(error) }) }) + const onAuthenticationEnd = (): void => { void stop() } + authentication.signal.addEventListener('abort', onAuthenticationEnd, { once: true }) + if (authentication.signal.aborted) onAuthenticationEnd() process.once('disconnect', () => { void stop() }) const { ctx } = await application + const canPublish = (): boolean => stopping === undefined && process.connected && !authentication.signal.aborted + if (!canPublish()) return + ctx.effect(() => () => { + authentication.signal.removeEventListener('abort', onAuthenticationEnd) + authentication.dispose() + }, 'desktop-host: authentication channel') installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId) control.updateTasks = installDesktopUpdateTaskControl(ctx) control.quitInspection = installDesktopQuitInspection(ctx) installPlatformSessionPublisher(ctx, (session) => { if (process.connected) process.send?.({ type: 'platform-session', session }) }) - const url = ctx.connection.authenticatedUrl(`${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}`) - if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections(ctx.connection.browserPeer) }, (error) => { if (error !== null) console.error(error) }) + await ctx.plugin(DesktopAuthentication, { readSecret: () => secret }).await() + if (!canPublish()) return + const admission = ctx.connection.authentication.authenticate({ + headers: { cookie: `dsh-desktop-session=${secret}` }, + }) + if ('rejection' in admission) throw new Error('Desktop authentication provider did not accept its startup credential') + const url = `${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}/` + const injections = ctx.webServer.collectIndexInjections(admission.peer) + if (!canPublish()) return + process.send?.({ type: 'ready', url, injections }, (error) => { if (error !== null) console.error(error) }) } if (import.meta.main) { diff --git a/apps/desktop-host/tests/authentication.spec.ts b/apps/desktop-host/tests/authentication.spec.ts new file mode 100644 index 0000000000..5e23f79c5c --- /dev/null +++ b/apps/desktop-host/tests/authentication.spec.ts @@ -0,0 +1,175 @@ +/** Desktop credential delivery and provider lifetime through the private IPC channel. */ +import { EventEmitter, once } from 'node:events' +import { randomBytes } from 'node:crypto' +import { Context } from '@deepseek-ai/cordis' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import WebServer from '@deepseek-ai/dsh-host-webserver' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import TypertGateway from '@deepseek-ai/dsh-api-gateway' +import RemoteAccess from '@deepseek-ai/dsh-api-remote-access' +import WebSocket from 'ws' +import OperatorFixture from '../../../packages/api/gateway/tests/operator-connect-fixture.ts' +import { expect, it, onTestFinished, vi } from 'vitest' +import { DesktopAuthenticationEnd, receiveDesktopSecret } from '../src/authentication.ts' +import * as DesktopAuthentication from '@deepseek-ai/dsh-host-authentication-desktop' + +class Channel extends EventEmitter { + connected = true +} +const secret = (): string => randomBytes(32).toString('base64url') + +it('listens before delivery and accepts one exact desktop credential message', async () => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + onTestFinished(() => { received.dispose() }) + const value = secret() + channel.emit('message', { type: 'unrelated' }) + channel.emit('message', { type: 'desktop-auth', secret: value }) + expect(await received.secret).toBe(value) + expect(received.signal.aborted).toBe(false) + expect(channel.listenerCount('message')).toBe(1) + received.dispose() + expect(channel.listenerCount('message')).toBe(0) + expect(channel.listenerCount('disconnect')).toBe(0) +}) + +it.each([ + { type: 'desktop-auth' }, + { type: 'desktop-auth', secret: 'bad-secret' }, + { type: 'desktop-auth', secret: 'A'.repeat(42) + 'B' }, + { type: 'desktop-auth', secret: 'A'.repeat(43), extra: true }, +])('rejects malformed desktop authentication without echoing input', async (message) => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + channel.emit('message', message) + await expect(received.secret).rejects.toThrow('Desktop authentication message is invalid') + expect(received.signal.aborted).toBe(true) + expect(received.signal.reason).not.toBeInstanceOf(DesktopAuthenticationEnd) + expect(String(received.signal.reason)).not.toContain('bad-secret') + expect(channel.listenerCount('message')).toBe(0) +}) + +it.each(['disconnected', 'shutdown'] as const)('distinguishes pending authentication ending on %s', async (kind) => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + if (kind === 'disconnected') channel.emit('disconnect') + else channel.emit('message', { type: 'shutdown' }) + await expect(received.secret).rejects.toBeInstanceOf(DesktopAuthenticationEnd) + expect(received.signal.reason).toMatchObject({ kind }) + expect(received.signal.aborted).toBe(true) + expect(channel.listenerCount('message')).toBe(0) + expect(channel.listenerCount('disconnect')).toBe(0) + channel.emit('message', { type: 'desktop-auth', secret: secret() }) + await expect(received.secret).rejects.toBe(received.signal.reason) +}) + +it.each(['disconnected', 'shutdown'] as const)('retains %s after credentials arrive before the receiver resumes', async (kind) => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + const value = secret() + channel.emit('message', { type: 'desktop-auth', secret: value }) + if (kind === 'disconnected') channel.emit('disconnect') + else channel.emit('message', { type: 'shutdown' }) + expect(await received.secret).toBe(value) + expect(() => { received.signal.throwIfAborted() }).toThrow(DesktopAuthenticationEnd) + expect(received.signal.reason).toMatchObject({ kind }) + expect(channel.listenerCount('message')).toBe(0) + expect(channel.listenerCount('disconnect')).toBe(0) +}) + +it('rejects disposal while waiting without treating it as parent shutdown', async () => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + received.dispose() + await expect(received.secret).rejects.toThrow('Desktop authentication receiver disposed') + expect(received.signal.reason).not.toBeInstanceOf(DesktopAuthenticationEnd) + expect(channel.listenerCount('message')).toBe(0) + expect(channel.listenerCount('disconnect')).toBe(0) +}) + +it('refuses a channel already disconnected before waiting', async () => { + const channel = new Channel() + channel.connected = false + const received = receiveDesktopSecret(channel) + await expect(received.secret).rejects.toBeInstanceOf(DesktopAuthenticationEnd) + expect(received.signal.reason).toMatchObject({ kind: 'disconnected' }) + expect(channel.listenerCount('message')).toBe(0) + expect(channel.listenerCount('disconnect')).toBe(0) +}) + +it.each([true, false])('rejects duplicate credentials before the receiver resumes (same: %s)', async (same) => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + const value = secret() + channel.emit('message', { type: 'desktop-auth', secret: value }) + channel.emit('message', { type: 'desktop-auth', secret: same ? value : secret() }) + expect(await received.secret).toBe(value) + expect(() => { received.signal.throwIfAborted() }).toThrow('Desktop authentication credential already received') + expect(received.signal.reason).not.toBeInstanceOf(DesktopAuthenticationEnd) + expect(channel.listenerCount('message')).toBe(0) + expect(channel.listenerCount('disconnect')).toBe(0) +}) + +it.each([true, false])('ends the channel on duplicate credentials (same: %s)', async (same) => { + const channel = new Channel() + const received = receiveDesktopSecret(channel) + const value = secret() + channel.emit('message', { type: 'desktop-auth', secret: value }) + await received.secret + channel.emit('message', { type: 'desktop-auth', secret: same ? value : secret() }) + expect(received.signal.aborted).toBe(true) + expect(String(received.signal.reason)).toContain('already received') + expect(String(received.signal.reason)).not.toContain(value) + expect(channel.listenerCount('message')).toBe(0) +}) + +it('authenticates real HTTP requests using its own Peer and withdraws with its owner', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await ctx.plugin(Connection).await() + await ctx.plugin(TypertRegistry).await() + await ctx.plugin(RemoteAccess).await() + await ctx.plugin(TypertGateway).await() + await ctx.plugin(OperatorFixture).await() + const value = secret() + const desktop = ctx.plugin(DesktopAuthentication, { readSecret: () => value }) + await desktop.await() + const admitted = ctx.connection.authentication.authenticate({ headers: { cookie: `dsh-desktop-session=${value}` } }) + if ('rejection' in admitted) throw new Error('Desktop fixture did not register its provider') + const desktopPeer = admitted.peer + expect(desktopPeer).not.toBe(ctx.connection.browserPeer) + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/identity', handler(req, res) { + const admitted = ctx.connection.admit(req) + if ('rejection' in admitted) { res.writeHead(admitted.rejection).end(); return } + res.end(admitted.peer.id) + } })) + const origin = ctx.webServer.getOrigin() + const request = async (cookie?: string): Promise<{ status: number; body: string }> => { + const response = await fetch(`${origin}/identity`, { headers: cookie === undefined ? {} : { cookie } }) + return { status: response.status, body: await response.text() } + } + expect((await request()).status).toBe(401) + expect((await request(`dsh-desktop-session=${secret()}`)).status).toBe(401) + expect((await request(`dsh-desktop-session=${value}; dsh-desktop-session=${value}`)).status).toBe(401) + expect(await request(`other=1; dsh-desktop-session=${value}`)).toEqual({ status: 200, body: desktopPeer.id }) + expect(await request(`dsh-desktop-session=${value}`)).toEqual({ status: 200, body: desktopPeer.id }) + const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, { + headers: { cookie: `dsh-desktop-session=${value}` }, + }) + const closed = once(socket, 'close') + onTestFinished(async () => { + if (socket.readyState !== WebSocket.CLOSED) socket.terminate() + await closed + }) + await once(socket, 'open') + const ready = once(socket, 'message') + socket.send(JSON.stringify({ type: 'open', streamId: 'desktop', endpoint: 'fixture/follow', payload: { args: { label: 'desktop' } } })) + await ready + expect(ctx.operatorConnectFixture.calls.get('desktop')?.peer).toBe(desktopPeer) + await desktop.dispose() + await closed + await vi.waitFor(() => { expect(ctx.operatorConnectFixture.calls.get('desktop')?.finished).toBe(true) }) + expect(desktopPeer.signal.aborted).toBe(true) + expect((await request(`dsh-desktop-session=${value}`)).status).toBe(401) +}) diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index c30951a3a4..b26c7e5db3 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -8,6 +8,7 @@ "src" ], "references": [ + { "path": "../../packages/host/authentication-desktop" }, { "path": "../../vendor/cordis" }, { "path": "../../packages/core/agent" }, { "path": "../../packages/jobs/jobs" }, diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 9ab02cc078..6bf82ad4e2 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 127ea90553cb6af7 zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: 37d36f8d57214336 - zh: ceb50c0fa866eb24 + en: 8b2a35655a384403 + zh: 8cb7c8138cae59db /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 @@ -27,8 +27,8 @@ en: 3724c53da4f7647b zh: 76ae549d43c99bb4 /deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies: - en: ee552473b21809bf - zh: f99db7657947b7e6 + en: 764bdc09fa8f5701 + zh: da7897e14434b43c /deepseek-harness-desktop/bundled-command-runtime: en: 372297005b57a08b zh: 074a635ac17e4362 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 20d6018932..9e225fe856 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -37,7 +37,9 @@ Electron caches the last confirmed UI language in `userData/desktop/locale-cache Desktop analytics follows the [product collection policy](../../packages/client/product-analytics/README.md), including its live application setting. Web usage is excluded. Update installation waits for its local analytics intake before locking API admission and stopping the Host. Intake has a one-second deadline; failure does not prevent installation, and collector delivery is not awaited. -The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it. Native Host requests send the current Host's authentication cookie explicitly, and no Electron session stores it; each Host start removes `dsh-auth-*` cookies that earlier releases left in the default session, because cookies ignore ports and would otherwise accompany every request to `127.0.0.1`. +The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it. Native Host requests explicitly send the Desktop credential as a `dsh-desktop-session` Cookie header, and no Electron session stores it; each Host start removes `dsh-auth-*` cookies that earlier releases left in the default session, because cookies ignore ports and would otherwise accompany every request to `127.0.0.1`. + +Electron generates a fresh random credential for each owned Host process. After the child's `starting` message, the main process sends it in a private `desktop-auth` IPC message. The Host creates an owner Peer and registers a Desktop authentication Provider before publishing its single `ready` message with the ordinary Host URL and that Peer's startup injections. Electron keeps the credential in main-process memory and attaches it to HTTP and WebSocket requests for that Host; the renderer receives boot data rather than the credential. Desktop proceeds directly after readiness, without the browser Token URL-to-Cookie exchange. While awaiting the credential, a shutdown request receives `shutdown-complete` and exits with status 0; parent disconnection exits with status 0 without starting the profile. Invalid or duplicate credential delivery remains an authentication failure. Desktop binds `127.0.0.1`, the address Electron dials for the ready URL and the WebSocket credential filter. WebSocket streams use `ws:` or `wss:` according to the Host listener; credentials require matching authority and scheme. @@ -123,7 +125,7 @@ The shared Desktop/SDK runtime builder omits directories named `tests` beneath N | Runtime | The application must run without a system Node.js or pnpm installation. | dsh runs under Electron with `ELECTRON_RUN_AS_NODE=1` and `--expose-internals` and every package operation uses the bundled pnpm. Package-manager configuration and the Host environment follow the user's settings. Package scripts use a `node` shell launcher that forwards to Electron. | | Package sources | Core installation at startup adds work even when offline. | `app.asar/dsh` carries a complete production dependency tree; the profile installs only external plugins. | | State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. | -| Transport | Web serving and authentication share one implementation. | Electron loads packaged Web assets; the Host supplies boot injections and authenticated APIs. | +| Transport | Web and Desktop share request admission and Peer-based authorization. | Electron loads packaged Web assets; its private Desktop Provider authenticates native Host requests, and the Host supplies startup injections for that Peer. | | Plugin changes | Desktop and Web need the same installation and activation behavior. | The main application uses the shared Web Plugin Manager and bundled pnpm. | | Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh runtime and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. | diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index bb874ce132..43b6c0c1df 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -37,7 +37,9 @@ Electron 在 `userData/desktop/locale-cache` 缓存最近确认的界面语言 桌面埋点遵循[产品采集策略](../../packages/client/product-analytics/README.zh.md)及其动态应用配置,不包含 Web 使用情况。安装更新会等待该操作的本地埋点接收请求结束,再锁定 API 准入并停止 Host。接收请求的时限为一秒,失败不会阻止安装,也不等待收集端完成发送。 -桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。原生 Host 请求会显式发送当前 Host 的认证 Cookie,任何 Electron session 都不保存该 Cookie;每次启动 Host 时都会移除早期版本遗留在默认 session 中的 `dsh-auth-*` Cookie,因为 Cookie 不区分端口,否则这些 Cookie 会随每个发往 `127.0.0.1` 的请求一并发送。 +桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。原生 Host 请求通过 `dsh-desktop-session` Cookie 头显式发送 Desktop 凭据,任何 Electron session 都不保存它;每次启动 Host 时都会移除早期版本遗留在默认 session 中的 `dsh-auth-*` Cookie,因为 Cookie 不区分端口,否则这些 Cookie 会随每个发往 `127.0.0.1` 的请求一并发送。 + +Electron 为每个自行启动的 Host 进程生成新的随机凭据。收到子进程的 `starting` 消息后,主进程通过私有 `desktop-auth` IPC 消息交付凭据。Host 创建 owner Peer 并注册 Desktop 认证 Provider,然后发送唯一的 `ready` 消息,携带普通 Host URL 和该 Peer 的启动注入。Electron 将凭据保存在主进程内存中,为发往该 Host 的 HTTP 和 WebSocket 请求附加凭据;渲染进程只接收启动数据。Desktop 在就绪后直接继续启动,无需浏览器 Token URL 换 Cookie 的步骤。等待凭据期间收到 shutdown 时,Host 回复 `shutdown-complete` 并以状态0退出;父通道断开时以状态0退出,不启动 profile。非法或重复凭据交付仍作为认证失败处理。 Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过滤器拨号的地址。WebSocket 流按 Host 监听器使用 `ws:` 或 `wss:`;附加凭据要求 authority 与 scheme 均匹配。 @@ -123,7 +125,7 @@ Desktop/SDK 共享运行时构建器在复制或签名产物前,裁剪 NumPy | 运行时 | 应用必须能够在没有系统 Node.js 或 pnpm 的机器上运行。 | dsh 通过设置 `ELECTRON_RUN_AS_NODE=1` 和 `--expose-internals` 的 Electron 运行,所有包操作都使用内置 pnpm。包管理器配置和 Host 环境遵循用户设置。包脚本通过 `node` shell 启动器转发给 Electron。 | | 包来源 | 即使离线,启动时安装核心依赖也会增加开销。 | `app.asar/dsh` 携带完整生产依赖树;profile 只安装外部插件。 | | 状态归属 | 共享可执行依赖图会让 CLI(命令行界面)与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 | -| 传输 | Web 服务与认证共享一套实现。 | Electron 加载打包的 Web 资源;Host 提供启动注入和经过认证的 API。 | +| 传输 | Web 与 Desktop 共享请求准入和基于 Peer 的授权。 | Electron 加载打包的 Web 资源;私有 Desktop Provider 认证原生 Host 请求,Host 提供该 Peer 的启动注入。 | | 插件变更 | Desktop 与 Web 需要一致的安装和激活行为。 | 主应用使用共享 Web 插件管理器和内置 pnpm。 | | 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh 运行时与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 | diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 1dbf6596ff..6be1ff8a3f 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -58,6 +58,9 @@ "devDependencies": { "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-app-boot": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", + "@deepseek-ai/dsh-host-authentication-desktop": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-general": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-browser": "workspace:*", "@deepseek-ai/dsh-home-paths": "workspace:*", diff --git a/apps/desktop/scripts/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts index fa2b2f5c4a..7f618b726e 100644 --- a/apps/desktop/scripts/smoke-runtime.ts +++ b/apps/desktop/scripts/smoke-runtime.ts @@ -185,8 +185,7 @@ export function apply(ctx) { timer = setTimeout(() => { reject(new Error('desktop runtime: Host readiness exceeded 120 seconds')) }, 120_000) })]) clearTimeout(timer) - const login = await fetch(ready.url, { redirect: 'manual' }) - const cookie = login.headers.getSetCookie().map(value => value.split(';')[0]).join('; ') + const cookie = ready.authenticationCookie const response = await fetch(new URL('/', ready.url), { headers: { cookie } }) if (response.status !== 200 || !(await response.text()).includes(' @@ -70,7 +83,7 @@ function isDesktopHostEvent(message: unknown): message is DesktopHostEvent { case 'shutdown-complete': return true case 'ready': - return typeof candidate.url === 'string' + return isOwnedHostUrl(candidate.url) case 'platform-session': { const session = candidate.session if (session === null) return true @@ -123,10 +136,12 @@ async function exitsWithin(exit: Promise, milliseconds: number): Promise void @@ -243,8 +259,24 @@ export class DesktopHostProcess { child.kill('SIGTERM') return } - if (message.type === 'starting') this.runId = message.runId - else if (message.type === 'ready') this.readyResolve({ url: message.url, injections: message.injections }) + if (message.type === 'starting') { + if (this.runId === undefined && !this.failureReported && !this.stopping) { + this.runId = message.runId + void this.#authentication.deliver(child).catch((error: unknown) => { + this.fail(error instanceof Error ? error : new Error(String(error))) + child.kill('SIGTERM') + }) + } + } + else if (message.type === 'ready') { + void this.#authentication.readyCookie().then((authenticationCookie) => { + if (this.failureReported || this.stopping) return + this.readyResolve({ url: message.url, injections: message.injections, authenticationCookie }) + }, (error: unknown) => { + this.fail(error instanceof Error ? error : new Error(String(error))) + child.kill('SIGTERM') + }) + } else if (message.type === 'platform-session') this.onPlatformSession?.(message.session) else if (message.type === 'shutdown-complete') { if (this.stopping) this.shutdownCompleted = true diff --git a/apps/desktop/src/host-protocol.ts b/apps/desktop/src/host-protocol.ts index dc0556fb52..3dc5724993 100644 --- a/apps/desktop/src/host-protocol.ts +++ b/apps/desktop/src/host-protocol.ts @@ -1,4 +1,4 @@ /** Release metadata for the Desktop Host lifecycle protocol. */ /** Lifecycle protocol generation recorded in Desktop release metadata. */ -export const DESKTOP_HOST_PROTOCOL_VERSION = 4 as const +export const DESKTOP_HOST_PROTOCOL_VERSION = 5 as const diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 8f9cd823a5..9232710910 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -43,7 +43,7 @@ import { desktopUpdateChannel } from './update-channel.ts' import { DesktopUpdateCoordinator } from './update-coordinator.ts' import { prepareDesktopUpdateWindow } from './update-window.ts' import { DesktopCommandManager } from './command-management.ts' -import { serveWebDocument, authenticateWebHost, forwardWebRequest, removeLegacyHostCookies } from './web-document.ts' +import { serveWebDocument, forwardWebRequest, removeLegacyHostCookies } from './web-document.ts' import { DesktopFatalRecovery } from './fatal-recovery.ts' import { pruneCrashReports, RendererConsoleTail, writeCrashReport, type CrashReportSource } from './crash-report.ts' import { OperationJournal } from './operation-journal.ts' @@ -545,7 +545,7 @@ async function main(): Promise { return { start: async () => { const ready = await host.start() - const cookie = await authenticateWebHost(ready.url) + const cookie = ready.authenticationCookie hostCookie = cookie hostUrl = ready.url void removeLegacyHostCookies(session.defaultSession.cookies, ready.url) diff --git a/apps/desktop/src/parent-authentication.ts b/apps/desktop/src/parent-authentication.ts new file mode 100644 index 0000000000..24ad49d953 --- /dev/null +++ b/apps/desktop/src/parent-authentication.ts @@ -0,0 +1,39 @@ +/** Parent-process ownership of the private Desktop authentication handshake. */ +import { randomBytes } from 'node:crypto' +import type { ChildProcess } from 'node:child_process' + +/** One credential and one delivery operation for an owned Host process. */ +export class DesktopParentAuthentication { + readonly #secret = randomBytes(32).toString('base64url') + #delivery: Promise | undefined + + /** + * Deliver the private credential once after the Host announces startup. + * @param channel - IPC channel of the owned Host process. + * @returns delivery completion; failures omit the credential and underlying IPC error. + */ + deliver(channel: Pick): Promise { + return this.#delivery ??= new Promise((resolve, reject) => { + const failed = (): void => { reject(new Error('dsh desktop host authentication handoff failed')) } + try { + channel.send({ type: 'desktop-auth', secret: this.#secret }, (error) => { + if (error !== null) failed() + else resolve() + }) + } catch (_ipcFailure) { + // IPC errors can retain the sent message; expose only the credential-free diagnostic. + failed() + } + }) + } + + /** + * Return the main-process credential after successful delivery. + * @returns Cookie header for this owned Host; rejects readiness before a handoff. + */ + async readyCookie(): Promise { + if (this.#delivery === undefined) throw new Error('dsh desktop host became ready before the authentication handoff') + await this.#delivery + return `dsh-desktop-session=${this.#secret}` + } +} diff --git a/apps/desktop/src/web-document.ts b/apps/desktop/src/web-document.ts index 15f289e14b..41bd08a729 100644 --- a/apps/desktop/src/web-document.ts +++ b/apps/desktop/src/web-document.ts @@ -35,20 +35,6 @@ export async function serveWebDocument(request: Request, root: string): Promise< }) } -/** - * Exchange the Host launch URL for an authority-bound browser cookie. - * @param url - Authenticated URL reported by the owned Host process. - * @returns Cookie header for requests forwarded to that Host. - */ -export async function authenticateWebHost(url: string): Promise { - const response = await fetch(url, { redirect: 'manual' }) - const cookie = response.headers.get('set-cookie') - await response.body?.cancel() - if (response.status !== 303 || cookie === null) throw new Error('Desktop Host authentication failed') - const end = cookie.indexOf(';') - return end < 0 ? cookie : cookie.slice(0, end) -} - /** Cookie store operations used to remove legacy Host authentication cookies. */ export interface HostCookieStore { get(filter: { url: string }): Promise @@ -91,7 +77,7 @@ const PLUGIN_BUNDLE_PATH = /^\/plugins\//u * no later launch can reuse. * @param request - Request from the application origin. * @param host - Owned Host URL. - * @param cookie - Host-issued authentication cookie. + * @param cookie - Desktop-private credential carried in the Cookie header for the owned Host. * @returns Host response without connection-level headers. */ export async function forwardWebRequest(request: Request, host: string, cookie: string): Promise { diff --git a/apps/desktop/src/welcome-backend.ts b/apps/desktop/src/welcome-backend.ts index 93648f7101..1c8fd919d0 100644 --- a/apps/desktop/src/welcome-backend.ts +++ b/apps/desktop/src/welcome-backend.ts @@ -39,7 +39,7 @@ function record(value: unknown): value is Record { /** * Connect the native HTTP client to the Desktop Host; every request sends `cookie` explicitly and uses no cookie jar. * @param hostUrl - URL of the running Desktop Host; only its origin is used. - * @param cookie - Cookie header returned by `authenticateWebHost` for this Host. + * @param cookie - Desktop-private authentication header for this owned Host. * @param send - HTTP client for Host requests. * @returns metadata reads and write-only credential operations over standard RPC. */ diff --git a/apps/desktop/tests/host-process.spec.ts b/apps/desktop/tests/host-process.spec.ts index 9a72fd2925..943c48fb92 100644 --- a/apps/desktop/tests/host-process.spec.ts +++ b/apps/desktop/tests/host-process.spec.ts @@ -1,4 +1,5 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import * as childProcess from 'node:child_process' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -7,6 +8,11 @@ import { OperationJournal } from '../src/operation-journal.ts' import { readOperationHistory } from '../src/operation-history.ts' import { renderCrashReport } from '../src/crash-report.ts' +vi.mock('node:child_process', async (importOriginal) => { + const original = await importOriginal() + return { ...original, spawn: vi.fn(original.spawn) } +}) + const roots: string[] = [] const hosts: DesktopHostProcess[] = [] @@ -14,6 +20,15 @@ const HTTP_HOST = ` import { createServer } from 'node:http' import { writeFileSync } from 'node:fs' import { join } from 'node:path' +let authenticationReceived = false +let receivedSecret = '' +let listening = false +let published = false +const publishReady = () => { + if (!authenticationReceived || !listening || published) return + published = true + process.send({ type: 'ready', url: 'http://127.0.0.1:' + server.address().port + '/' }) +} const server = createServer((request, response) => { if (request.url === '/fatal') { process.send({ type: 'fatal', message: 'plugin unavailable' }) @@ -27,12 +42,17 @@ const server = createServer((request, response) => { return } response.setHeader('content-type', 'application/json') - response.end(JSON.stringify({runtime: process.argv[2], profile: process.argv[3], cwd: process.cwd(), nodePath: process.env.NODE_PATH, registry: process.env.NPM_CONFIG_REGISTRY, nodeOptions: process.env.NODE_OPTIONS, runAsNode: process.env.ELECTRON_RUN_AS_NODE, internals: process.execArgv.includes('--expose-internals')})) -}) -server.listen(0, '127.0.0.1', () => { - process.send({ type: 'ready', url: 'http://127.0.0.1:' + server.address().port + '/?token=fixture' }) + response.end(JSON.stringify({runtime: process.argv[2], profile: process.argv[3], cwd: process.cwd(), nodePath: process.env.NODE_PATH, registry: process.env.NPM_CONFIG_REGISTRY, nodeOptions: process.env.NODE_OPTIONS, runAsNode: process.env.ELECTRON_RUN_AS_NODE, internals: process.execArgv.includes('--expose-internals'), privateAuth: authenticationReceived && /^[A-Za-z0-9_-]{43}$/.test(receivedSecret) && !JSON.stringify(process.argv).includes(receivedSecret) && !JSON.stringify(process.env).includes(receivedSecret)})) }) +server.listen(0, '127.0.0.1', () => { listening = true; publishReady() }) process.on('message', message => { + if (message.type === 'desktop-auth') { + if (authenticationReceived || !/^[A-Za-z0-9_-]{43}$/.test(message.secret)) throw new Error('invalid authentication handoff') + authenticationReceived = true + receivedSecret = message.secret + publishReady() + return + } if (message.type === 'file-drag-cancel') { process.send({ type: 'file-drag-resource', requestId: message.requestId, resource: null }) return @@ -65,6 +85,7 @@ process.on('message', message => { }) server.closeAllConnections() }) +process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) ` function projectWithHost(source = HTTP_HOST): string { @@ -93,8 +114,11 @@ afterEach(async () => { describe('desktop host process', () => { it('retains the announced run identity when startup fails before readiness', async () => { const runtime = projectWithHost(` +process.once('message', message => { + if (message.type !== 'desktop-auth') throw new Error('expected authentication') + process.send({ type: 'fatal', message: 'profile startup failed', diagnostic: 'required plugin failed' }, () => process.disconnect()) +}) process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) -process.send({ type: 'fatal', message: 'profile startup failed', diagnostic: 'required plugin failed' }, () => process.disconnect()) `) const host = hostProcess(runtime) const failure: unknown = await host.start().catch((error: unknown) => error) @@ -111,7 +135,10 @@ process.send({ type: 'fatal', message: 'profile startup failed', diagnostic: 're const failed = Promise.withResolvers() const runtime = projectWithHost(` process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) -process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' }, () => { ${trigger} }) +process.once('message', message => { + if (message.type !== 'desktop-auth') throw new Error('expected authentication') + process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' }, () => { ${trigger} }) +}) `) const host = hostProcess(runtime, runtime, failed.resolve) await host.start() @@ -224,8 +251,9 @@ ${HTTP_HOST}`) 'process.exit(0)', ])('refuses installation when exit lacks successful teardown acknowledgement: %s', async (exit) => { const host = hostProcess(projectWithHost(` - process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' }) + process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) process.on('message', message => { + if (message.type === 'desktop-auth') process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' }) if (message.type === 'shutdown') process.stderr.write('token=fixture-secret', () => { ${exit} }) }) `)) @@ -238,12 +266,90 @@ ${HTTP_HOST}`) await expect(host.stop()).resolves.toBeUndefined() }) - it('returns the Web authentication URL and waits for graceful shutdown', async () => { + it('rejects readiness before the private authentication handoff', async () => { + const host = hostProcess(projectWithHost("process.send({ type: 'ready', url: 'http://127.0.0.1:3080/' })")) + await expect(host.start()).rejects.toThrow('authentication handoff') + }) + + it.each([ + 'https://example.test/', + 'http://127.0.0.1:3080/?token=untrusted', + 'http://user:password@127.0.0.1:3080/', + 'http://127.0.0.1:3080/other', + ])('rejects an unexpected ready address before using a credential: %s', async (url) => { + const host = hostProcess(projectWithHost(` +process.on('message', message => { + if (message.type === 'desktop-auth') process.send({ type: 'ready', url: ${JSON.stringify(url)} }) +}) +process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }) +`)) + await expect(host.start()).rejects.toThrow('invalid IPC event') + }) + + it('provides a private per-child authentication Cookie with the ordinary ready address', async () => { + const source = ` +import { randomUUID } from 'node:crypto' +process.on('message', message => { + if (message.type === 'desktop-auth') { + if (!/^[A-Za-z0-9_-]{43}$/.test(message.secret)) throw new Error('invalid credential') + process.send({ type: 'ready', url: 'http://127.0.0.1:3080/', injections: [] }) + } + if (message.type === 'shutdown') process.send({ type: 'shutdown-complete' }, () => process.disconnect()) +}) +process.send({ type: 'starting', runId: randomUUID() }) +` + const runtime = projectWithHost(source) + const first = await hostProcess(runtime).start() + const second = await hostProcess(runtime).start() + expect(first.url).toBe('http://127.0.0.1:3080/') + expect(first.authenticationCookie).toMatch(/^dsh-desktop-session=[A-Za-z0-9_-]{43}$/) + expect(first.authenticationCookie).not.toBe(second.authenticationCookie) + expect(first.injections).toEqual([]) + }) + + it('sends the credential once even when the child repeats starting', async () => { + const source = HTTP_HOST.replace("process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' })", + "process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' }); process.send({ type: 'starting', runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' })") + const host = hostProcess(projectWithHost(source)) + const ready = await host.start() + expect((await fetch(ready.url)).status).toBe(200) + await host.stop(true) + }) + + it('reports a credential-free failure when the private IPC send fails', async () => { + const realSpawn = (await vi.importActual('node:child_process')).spawn + let secret = '' + vi.mocked(childProcess.spawn).mockImplementationOnce((...args) => { + const child = Reflect.apply(realSpawn, childProcess, args) + const send = child.send.bind(child) + vi.spyOn(child, 'send').mockImplementation((message, ...rest) => { + if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'desktop-auth') { + secret = 'secret' in message ? String(message.secret) : '' + const callback = rest.at(-1) + if (typeof callback !== 'function') throw new Error('missing send callback') + callback(new Error(`failed message ${secret}`)) + return false + } + return Reflect.apply(send, child, [message, ...rest]) + }) + return child + }) + const failures: Error[] = [] + const host = hostProcess(projectWithHost(), undefined, error => failures.push(error)) + await expect(host.start()).rejects.toThrow('authentication handoff failed') + await host.stop() + expect(secret).toMatch(/^[A-Za-z0-9_-]{43}$/) + expect(failures).toHaveLength(1) + expect(String(failures[0])).not.toContain(secret) + }) + + it('returns the ordinary Host URL and waits for graceful shutdown', async () => { const runtime = projectWithHost() const failure = vi.fn() const host = hostProcess(runtime, runtime, failure) const ready = await host.start() - expect(new URL(ready.url).searchParams.get('token')).toBe('fixture') + expect(new URL(ready.url).search).toBe('') + expect(ready.authenticationCookie).toMatch(/^dsh-desktop-session=[A-Za-z0-9_-]{43}$/) expect(await host.start()).toEqual(ready) expect((await fetch(ready.url)).status).toBe(200) await host.stop() @@ -272,7 +378,7 @@ ${HTTP_HOST}`) await expect.poll(() => failure.mock.calls.length).toBe(1) await host.stop() expect(failure).toHaveBeenCalledTimes(1) - expect(failure).toHaveBeenCalledWith(new Error('plugin unavailable')) + expect(failure).toHaveBeenCalledWith(expect.objectContaining({ message: 'plugin unavailable', hostRunId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' })) }) it('reports a child crash after readiness with its stderr diagnostic', async () => { @@ -282,7 +388,7 @@ ${HTTP_HOST}`) const { url } = await host.start() await fetch(new URL('/crash', url)) await expect.poll(() => failure.mock.calls.length).toBe(1) - expect(failure).toHaveBeenCalledWith(new Error('dsh desktop host exited with 7: plugin crashed')) + expect(failure).toHaveBeenCalledWith(expect.objectContaining({ message: 'dsh desktop host exited with 7: plugin crashed', hostRunId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8' })) }) it('retains only recent diagnostics from a noisy child', async () => { @@ -312,7 +418,7 @@ ${HTTP_HOST}`) }) const { url } = await host.start() const response = await fetch(url) - expect(await response.json()).toEqual({ runtime, profile, cwd: realpathSync(profile), nodePath: '/custom', registry: 'https://registry.example.test/', nodeOptions: '--no-warnings', runAsNode: '1', internals: true }) + expect(await response.json()).toEqual({ runtime, profile, cwd: realpathSync(profile), nodePath: '/custom', registry: 'https://registry.example.test/', nodeOptions: '--no-warnings', runAsNode: '1', internals: true, privateAuth: true }) }) it.each([ diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 17e16cec09..c20ea6e900 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -23,7 +23,7 @@ const fileDrag = vi.hoisted(() => ({ dispose: vi.fn<() => Promise>(), inst vi.mock('../src/file-drag.ts', () => ({ installDesktopFileDrag: () => { fileDrag.install(); return fileDrag.dispose } })) vi.mock('../src/web-document.ts', () => ({ - authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn(), + serveWebDocument: vi.fn(), forwardWebRequest: vi.fn(), removeLegacyHostCookies: harness.removeLegacyHostCookies, })) vi.mock('../src/operation-report-job.ts', () => ({ runOperationReportJob: vi.fn(async () => ({ appended: false, timedOut: false, cancelled: false })) })) @@ -155,12 +155,12 @@ const harness = await vi.hoisted(async () => { class FakeHost { readonly updateTasks = vi.fn(async (_action: 'inspect' | 'lock' | 'unlock') => false) readonly inspectQuit = vi.fn(async () => ({ activeTasks: false, scheduledTasks: false })) - url = 'http://127.0.0.1:3080/?token=test' + url = 'http://127.0.0.1:3080/' fetch = vi.fn(async () => Response.json({ hasApiKey: true, writable: true, localePreference: null, themePreference: 'system' })) readonly ready = deferred() readonly exited = deferred() readonly stopping = deferred() - readonly start = vi.fn(() => { hostStarted.resolve(); return this.ready.promise.then(() => ({ url: this.url, injections: [] })) }) + readonly start = vi.fn(() => { hostStarted.resolve(); return this.ready.promise.then(() => ({ url: this.url, injections: [], authenticationCookie: 'dsh-desktop-session=test-private' })) }) readonly stop = vi.fn(() => { this.stopping.resolve() this.ready.reject(new Error('child stopped')) @@ -1465,11 +1465,11 @@ describe('desktop main startup', () => { await harness.preparing.promise harness.prepared.resolve() await harness.hostStarted.promise - harness.hosts[0]!.url = `${protocol}//127.0.0.1:3080/?token=test` + harness.hosts[0]!.url = `${protocol}//127.0.0.1:3080/` harness.hosts[0]!.ready.resolve() await Promise.resolve(invoke(DESKTOP_IPC.boot)) - expect(harness.connectWelcome).toHaveBeenCalledWith(`${protocol}//127.0.0.1:3080/?token=test`, 'test-cookie') - expect(harness.removeLegacyHostCookies).toHaveBeenCalledWith(harness.hostCookies, `${protocol}//127.0.0.1:3080/?token=test`) + expect(harness.connectWelcome).toHaveBeenCalledWith(`${protocol}//127.0.0.1:3080/`, 'dsh-desktop-session=test-private') + expect(harness.removeLegacyHostCookies).toHaveBeenCalledWith(harness.hostCookies, `${protocol}//127.0.0.1:3080/`) const handler = harness.socketHeaders.mock.calls[0]![1] as ( details: { url: string; webContentsId: number; requestHeaders: Record }, callback: (result: unknown) => void, @@ -1479,7 +1479,7 @@ describe('desktop main startup', () => { const details = { url: `${socketProtocol}//127.0.0.1:3080/api/remote.mux`, webContentsId: 42, requestHeaders: { Origin: 'dsh-app://app' } } handler(details, callback) expect(callback).toHaveBeenLastCalledWith({ requestHeaders: { - origin: `${protocol}//127.0.0.1:3080`, cookie: 'test-cookie', 'sec-fetch-site': 'same-origin', + origin: `${protocol}//127.0.0.1:3080`, cookie: 'dsh-desktop-session=test-private', 'sec-fetch-site': 'same-origin', } }) handler({ ...details, requestHeaders: { Origin: 'https://other.example' } }, callback) expect(callback).toHaveBeenLastCalledWith({ cancel: true }) @@ -3069,7 +3069,7 @@ describe('desktop main startup', () => { await harness.dialogShown.promise preferences.resolve(Response.json({ hasApiKey: true, localePreference: null })) await startup - expect(harness.windows[0]!.urls).not.toContain('http://127.0.0.1:3080/?token=test') + expect(harness.windows[0]!.urls).not.toContain('http://127.0.0.1:3080/') const failureDialog = harness.dialog.showMessageBox.mock.calls[0]![0] as { detail: string } expect(failureDialog.detail).toContain('backend exited during startup preferences') expect(harness.windows[0]!.show).not.toHaveBeenCalled() diff --git a/apps/desktop/tests/office-resources.e2e.ts b/apps/desktop/tests/office-resources.e2e.ts index ae626554e9..21316dcfb1 100644 --- a/apps/desktop/tests/office-resources.e2e.ts +++ b/apps/desktop/tests/office-resources.e2e.ts @@ -67,12 +67,10 @@ describe.skipIf(!existsSync(builtHost))('built Desktop Host Office resources', ( const primaryRuntime = mode === 'relative-source' ? 'runtime/primary-runtime' : join(runtime, 'primary-runtime') host = new DesktopHostProcess(process.execPath, project, paths.profile, undefined, process.env, (error) => { failures.push(error) }, primaryRuntime) - const { url } = await host.start() - // The authenticated URL exchanges its token for a session cookie by redirecting. - const response = await fetch(url, { redirect: 'manual' }) + const { url, authenticationCookie: cookie } = await host.start() + const response = await fetch(url, { headers: { cookie }, redirect: 'manual' }) await response.body?.cancel() - expect(response.status).toBe(303) - const cookie = response.headers.getSetCookie().map(value => value.split(';')[0]).join('; ') + expect(response.status).toBe(200) const probe = await fetch(new URL(`/${SKILL_PROBE}`, url), { headers: { cookie } }) const body = await probe.text() expect(probe.status, body).toBe(200) diff --git a/apps/desktop/tests/smoke-runtime.spec.ts b/apps/desktop/tests/smoke-runtime.spec.ts index 44b9cd9056..cc6b9602af 100644 --- a/apps/desktop/tests/smoke-runtime.spec.ts +++ b/apps/desktop/tests/smoke-runtime.spec.ts @@ -1,7 +1,39 @@ -/** Behavioral checks for packaged Office skill probe results. */ +/** Packaged runtime HTTP authentication and Office skill probe results. */ -import { describe, expect, it } from 'vitest' -import { assertOfficeSkillsLoadable } from '../scripts/smoke-runtime.ts' +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import WebServer from '@deepseek-ai/dsh-host-webserver' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import * as DesktopAuthentication from '@deepseek-ai/dsh-host-authentication-desktop' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { assertOfficeSkillsLoadable, smokeDesktopRuntime } from '../scripts/smoke-runtime.ts' +import { runtimeFixture } from './runtime-fixture.ts' + +const boundary = vi.hoisted(() => ({ + start: vi.fn<() => Promise<{ url: string; injections: []; authenticationCookie: string }>>(), + stop: vi.fn(async () => {}), + run: vi.fn<(_executable: string, _args: string[], _options: { cwd?: string }) => Promise<{ stdout: string; stderr: string }>>(), +})) +vi.mock('../src/host-process.ts', () => ({ + DesktopHostProcess: class { + start = boundary.start + stop = boundary.stop + }, +})) +vi.mock('node:child_process', async (importOriginal) => { + const { promisify } = await import('node:util') + return { ...await importOriginal(), + execFile: Object.assign(vi.fn(), { [promisify.custom]: boundary.run }) } +}) +afterEach(() => { + boundary.start.mockReset() + boundary.stop.mockClear() + boundary.run.mockReset() + vi.restoreAllMocks() +}) const loadedSkills = [ { name: 'office', bytes: 772 }, @@ -10,6 +42,83 @@ const loadedSkills = [ { name: 'office-xlsx', bytes: 5611 }, ] +it('uses the private readiness Cookie for every packaged runtime HTTP probe', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-smoke-auth-')) + const ctx = new Context() + onTestFinished(async () => { + await ctx.fiber.dispose() + if (!isAbsolute(root) || dirname(root) !== resolve(tmpdir()) || !basename(root).startsWith('dsh-smoke-auth-')) { + throw new Error(`refusing unexpected fixture cleanup path: ${root}`) + } + await rm(root, { recursive: true, force: true }) + }) + const runtime = runtimeFixture(join(root, 'payload')) + const resources = join(root, 'runtime') + const primary = join(resources, 'primary-runtime') + mkdirSync(primary, { recursive: true }) + writeFileSync(join(primary, 'runtime.json'), JSON.stringify({ + desktopVersion: '1.0.0', platform: process.platform, arch: process.arch, + python: '3.12.0', pythonPackages: {}, + })) + const secret = Buffer.alloc(32, 7).toString('base64url') + const cookie = `dsh-desktop-session=${secret}` + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await ctx.plugin(Connection).await() + await ctx.plugin(DesktopAuthentication, { readSecret: () => secret }).await() + const requests: { path: string | undefined; cookie: string | undefined }[] = [] + ctx.on('webserver/request', async (request, _response, next) => { + requests.push({ path: request.url, cookie: request.headers.cookie }) + await next() + }) + ctx.effect(() => ctx.webServer.registerFallback({ + handler(request, response) { + const path = request.url + if (path === '/') response.end('packaged fixture') + else if (path === '/desktop-smoke') response.end('plugin route ready') + else if (path === '/desktop-smoke-install') response.end('{}') + else if (path === '/desktop-smoke-installed') response.end('installed plugin ready') + else if (path === '/desktop-smoke-skills') response.end(JSON.stringify(loadedSkills)) + else if (path?.startsWith('/desktop-smoke-office/')) response.end('%PDF-1.7\nfixture\n%%EOF') + else if (path?.startsWith('/desktop-smoke-office-operations/')) response.end(JSON.stringify({ + images: ['89504e470d0a1a0a'], converted: '504b0304', recalculated: path.endsWith('/xlsx') ? '504b0304' : null, + })) + else response.writeHead(404).end() + }, + })) + boundary.start.mockResolvedValue({ url: ctx.webServer.getOrigin(), injections: [], authenticationCookie: cookie }) + let smokeHome: string | undefined + // Only package-manager and Office subprocess work is substituted; HTTP admission is real. + boundary.run.mockImplementation(async (_executable, args, options) => { + if (options.cwd === undefined) { + const home = args.at(-1)! + for (const extension of ['docx', 'xlsx', 'pptx']) writeFileSync(join(home, `input.${extension}`), 'fixture') + } else { + const home = options.cwd + smokeHome = home + const installed = join(home, 'profiles', 'desktop', 'node_modules', 'desktop-installed-smoke-plugin') + if (args.includes('add')) cpSync(join(home, 'desktop-installed-smoke-plugin'), installed, { recursive: true }) + else { + if (!args.includes('remove') || !isAbsolute(home) || dirname(home) !== resolve(tmpdir()) + || !basename(home).startsWith('dsh-desktop-smoke-')) throw new Error('unexpected package-manager fixture operation') + expect(readFileSync(join(installed, 'index.js'), 'utf8')).toContain('installed plugin ready') + rmSync(installed, { recursive: true }) + } + } + return { stdout: '', stderr: '' } + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + await smokeDesktopRuntime(join(root, 'payload'), process.execPath, runtime, {}, resources) + expect(requests.map(request => request.path)).toEqual([ + '/', '/desktop-smoke', '/desktop-smoke-install', '/desktop-smoke-installed', '/desktop-smoke-skills', + '/desktop-smoke-office/docx', '/desktop-smoke-office/xlsx', '/desktop-smoke-office/pptx', + '/desktop-smoke-office-operations/docx', '/desktop-smoke-office-operations/xlsx', '/desktop-smoke-office-operations/pptx', + ]) + expect(requests.every(request => request.cookie === cookie)).toBe(true) + expect(boundary.stop).toHaveBeenCalledOnce() + expect(smokeHome).toBeDefined() + expect(existsSync(smokeHome!)).toBe(false) +}) + describe('assertOfficeSkillsLoadable', () => { it('accepts all four Office skills with nonempty bodies and no path', () => { expect(() => { assertOfficeSkillsLoadable(loadedSkills) }).not.toThrow() diff --git a/apps/desktop/tests/web-document.spec.ts b/apps/desktop/tests/web-document.spec.ts index 6507712ef6..b882b3c769 100644 --- a/apps/desktop/tests/web-document.spec.ts +++ b/apps/desktop/tests/web-document.spec.ts @@ -2,7 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest' import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { authenticateWebHost, forwardWebRequest, removeLegacyHostCookies, serveWebDocument } from '../src/web-document.ts' +import { forwardWebRequest, removeLegacyHostCookies, serveWebDocument } from '../src/web-document.ts' const roots: string[] = [] afterEach(async () => { @@ -27,26 +27,21 @@ it('serves the Web entry and assets without starting or contacting a Host', asyn expect((await serveWebDocument(new Request('dsh-app://app/missing.js'), root)).status).toBe(404) }) -it('requires the Host authentication exchange and retains only its cookie value', async () => { - const fetch = vi.fn().mockResolvedValueOnce(new Response(null, { status: 303, headers: { 'set-cookie': 'session=owned; HttpOnly; SameSite=Strict' } })) - .mockResolvedValueOnce(new Response('unauthorized', { status: 401 })) - vi.stubGlobal('fetch', fetch) - expect(await authenticateWebHost('http://127.0.0.1:1234/?token=owned')).toBe('session=owned') - await expect(authenticateWebHost('http://127.0.0.1:1234/')).rejects.toThrow('authentication failed') -}) - it('forwards upload bytes and cancellation with Host credentials while keeping the response streaming', async () => { const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('stream')); controller.close() } }) const fetch = vi.fn().mockResolvedValue(new Response(body, { headers: { 'content-encoding': 'gzip', 'set-cookie': 'private' } })) vi.stubGlobal('fetch', fetch) const request = new Request('dsh-app://app/api/upload?name=file', { - method: 'POST', body: 'upload bytes', headers: { origin: 'dsh-app://app', cookie: 'untrusted' }, + method: 'POST', body: 'upload bytes', + headers: { origin: 'dsh-app://app', cookie: 'untrusted', host: 'untrusted', 'sec-fetch-site': 'cross-site', accept: 'text/plain' }, }) - const response = await forwardWebRequest(request, 'http://127.0.0.1:1234/?token=secret', 'session=owned') + const response = await forwardWebRequest(request, 'http://127.0.0.1:1234/', 'dsh-desktop-session=owned') const [target, init] = fetch.mock.calls[0] as [URL, RequestInit] expect(target.href).toBe('http://127.0.0.1:1234/api/upload?name=file') - expect(new Headers(init.headers).get('cookie')).toBe('session=owned') - expect(new Headers(init.headers).get('origin')).toBeNull() + expect(new Headers(init.headers).get('cookie')).toBe('dsh-desktop-session=owned') + for (const name of ['origin', 'host', 'sec-fetch-site']) expect(new Headers(init.headers).get(name)).toBeNull() + expect(new Headers(init.headers).get('accept')).toBe('text/plain') + expect(request.headers.get('cookie')).toBe('untrusted') expect(init.signal).toBe(request.signal) expect(init.body).toBe(request.body) expect(response.headers.get('set-cookie')).toBeNull() diff --git a/apps/desktop/tests/welcome-flow.e2e.ts b/apps/desktop/tests/welcome-flow.e2e.ts index f298fd10fb..ff0e21f590 100644 --- a/apps/desktop/tests/welcome-flow.e2e.ts +++ b/apps/desktop/tests/welcome-flow.e2e.ts @@ -9,7 +9,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { DesktopHostProcess } from '../src/host-process.ts' import { desktopClientMetadata } from '../src/client-metadata.ts' import { connectDesktopWelcome, type DesktopWelcomeBackend } from '../src/welcome-backend.ts' -import { authenticateWebHost } from '../src/web-document.ts' import { builtHost, prepareDesktopHome } from './harness.ts' afterEach(() => { vi.unstubAllEnvs() }) @@ -90,9 +89,9 @@ describe.skipIf(!existsSync(builtHost))('built Desktop welcome flow', () => { await host?.stop() host = new DesktopHostProcess(process.execPath, project, paths.profile, undefined, process.env, undefined, join(root, 'runtime', 'primary-runtime')) - const { url } = await host.start() + const { url, authenticationCookie } = await host.start() hostOrigin = new URL(url).origin - backend = connectDesktopWelcome(url, await authenticateWebHost(url)) + backend = connectDesktopWelcome(url, authenticationCookie) } const status = async () => backend.read() const fingerprint = (): string => createHash('sha256') diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index 1f9bc8a5cf..9e365f932b 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -1,5 +1,5 @@ vi.mock('../src/web-document.ts', () => ({ - authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn(), removeLegacyHostCookies: async () => {}, + serveWebDocument: vi.fn(), forwardWebRequest: vi.fn(), removeLegacyHostCookies: async () => {}, })) /** Welcome startup uses the Host before transitioning to the workspace. */ @@ -22,7 +22,7 @@ const state = vi.hoisted(() => ({ status: 'signed-out', attempt: null, links: { usageUrl: '', topUpUrl: '' }, }), quit: vi.fn(), - startHost: vi.fn().mockResolvedValue({ url: 'http://127.0.0.1:3080/?token=test', injections: [] }), + startHost: vi.fn().mockResolvedValue({ url: 'http://127.0.0.1:3080/', injections: [], authenticationCookie: 'dsh-desktop-session=fixture' }), stopHost: vi.fn<() => Promise>().mockResolvedValue(undefined), loadWorkspace: vi.fn<(url: string) => Promise>().mockResolvedValue(undefined), showWorkspace: vi.fn(), diff --git a/apps/web/tests/account-login.e2e.ts b/apps/web/tests/account-login.e2e.ts index 029e6a3cc1..5c44cb0684 100644 --- a/apps/web/tests/account-login.e2e.ts +++ b/apps/web/tests/account-login.e2e.ts @@ -93,7 +93,7 @@ async function mockPlatform() { await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) const address = server.address() if (address === null || typeof address === 'string') throw new Error('account login: missing mock listener') - const origin = `http://127.0.0.1:${String(address.port)}` + const origin = `http://localhost:${String(address.port)}` return { origin, inits, pages, avatarRequests: () => avatarRequests, notificationLists: () => notificationLists, close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), @@ -132,8 +132,10 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain const menu = page.getByRole('button', { name: 'Account menu', exact: true }) await menu.click() const tab = context.waitForEvent('page') + const callback = context.waitForEvent('request', request => new URL(request.url()).pathname === '/oauth/callback') await page.getByRole('menuitem', { name: 'Sign in', exact: true }).click() const authorization = await tab + expect((await (await callback).allHeaders())['sec-fetch-site']).toBe('cross-site') await authorization.waitForURL(url => url.pathname === '/dsh/authorized', { timeout: 30_000 }) expect(await authorization.evaluate(() => window.opener === null)).toBe(true) await expect.poll(() => menu.textContent(), { timeout: 30_000 }).toBe('Web User') diff --git a/apps/web/tests/desktop-onboarding.e2e.ts b/apps/web/tests/desktop-onboarding.e2e.ts index 8283fb7125..058f466457 100644 --- a/apps/web/tests/desktop-onboarding.e2e.ts +++ b/apps/web/tests/desktop-onboarding.e2e.ts @@ -5,7 +5,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { connectDesktopWelcome } from '../../desktop/src/welcome-backend.ts' -import { authenticateWebHost } from '../../desktop/src/web-document.ts' import { chromium, type Browser, type Page } from 'playwright' import { afterEach, beforeEach, describe, expect, it, onTestFailed } from 'vitest' import { credentialKey, credentialRef } from '@deepseek-ai/dsh-credentials' @@ -109,7 +108,10 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => async function desktopPage(locale = ZH_BROWSER_LOCALE): Promise { const opened = await browser.newPage({ viewport: { width: 1280, height: 840 }, locale, reducedMotion: 'reduce' }) - const welcome = connectDesktopWelcome(scaffold.baseUrl, await authenticateWebHost(scaffold.authenticatedUrl)) + const welcome = connectDesktopWelcome(scaffold.baseUrl, '', (input, init) => { + const target = new URL(input) + return scaffold.hostFetch(`${target.pathname}${target.search}`, init) + }) await opened.exposeFunction('__onboardingHasApiKey', async () => (await welcome.read()).hasApiKey) await opened.addInitScript(() => { Object.defineProperty(globalThis, 'dshOnboarding', { value: { diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index b394c3cd96..854be934b1 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -651,11 +651,11 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise() + let startupLoginUrl: URL + const originalLog = console.log + console.log = (...args: unknown[]) => { + const line = args.length === 1 && typeof args[0] === 'string' ? args[0] : '' + const match = /^dsh web: (http:\/\/127\.0\.0\.1:\d+\/\?token=[A-Za-z0-9_-]+)$/u.exec(line) + if (match !== null) { + const url = new URL(match[1]!) + const boundPort = ctx.get('webServer')?.port + if (boundPort !== undefined && url.port === String(boundPort)) { + startupLogin.resolve(url) + return + } + } + originalLog(...args) + } + let startupTimer: ReturnType | undefined + try { + await mountRootInclude(ctx, rootConfig, readProfilePatches('dsh', profileContext)) + await ctx.loader.await() + await auditStartupEntries(ctx, 'web e2e scaffold') + startupTimer = setTimeout(() => { + startupLogin.reject(new Error('web e2e scaffold: token plugin did not publish its login URL')) + }, 10_000) + startupLoginUrl = await startupLogin.promise + } finally { + clearTimeout(startupTimer) + console.log = originalLog + } if (options.developerTools !== undefined) { await ctx.settings.update('ui-settings', { enabled: options.developerTools }) } @@ -930,7 +958,9 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise provider.id === 'deepseek-messages')).toBe(false) expect(ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'deepseek-official', model: 'deepseek-flash' }) - const index = await fetch(`http://127.0.0.1:${String(ctx.webServer.port)}`, { + const index = await scaffold.hostFetch('/', { headers: { 'accept-encoding': 'gzip' }, }) + expect(index.status).toBe(200) + expect(index.headers.get('content-type')).toContain('text/html') expect(index.headers.get('content-encoding')).toBe('gzip') expect(index.headers.get('vary')).toContain('Accept-Encoding') await index.body?.cancel() diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index a7c01f3ef1..6b119b1c3b 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 78778294644e7b42 - zh: 2985cca0ffc69256 + en: 3dd4fb581635c873 + zh: 40647337f0ea2a02 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 943631f1b0..3200af3545 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -36,6 +36,9 @@ flowchart LR svc_connection["ctx.connection
Authenticated browser transport"] pkg_api_gateway["api-gateway"] pkg_host_frontend_static["host-frontend-static"] + svc_connection_authentication["ctx.connection.authentication
Connection authentication provider registry"] + pkg_host_authentication_token["host-authentication-token"] + pkg_host_authentication_desktop["host-authentication-desktop"] pkg_experimental_forge["experimental-forge"] svc_forge["ctx.forge
Code host change requests"] pkg_experimental_forge_github["experimental-forge-github"] @@ -344,6 +347,7 @@ flowchart LR pkg_bash_sandbox --> svc_shell pkg_browser_use --> svc_browserUse pkg_client_connection --> svc_connection + pkg_client_connection --> svc_connection_authentication pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics @@ -390,6 +394,8 @@ flowchart LR pkg_goal --> svc_goals pkg_headless --> svc_headlessStartup pkg_hmr --> svc_hmr + pkg_host_authentication_desktop --> svc_connection_authentication + pkg_host_authentication_token --> svc_connection_authentication pkg_host_directory_picker --> svc_directoryPicker pkg_host_directory_picker_browse --> svc_directoryPicker pkg_host_directory_picker_native --> svc_directoryPicker @@ -514,6 +520,7 @@ flowchart LR svc_configEditor --> pkg_settings svc_connection --> pkg_api_gateway svc_connection --> pkg_host_frontend_static + svc_connection_authentication --> pkg_client_connection svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller svc_credentials --> pkg_llm_deepseek @@ -667,7 +674,8 @@ flowchart LR | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | -| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | +| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Applies source policy and shared HTTP request dispatch; credential verification belongs to ConnectionAuthentication, and API adapters register endpoints and streams. | +| `ctx.connection.authentication` | `seam` | [`client-connection`](../packages/client/connection) | [`host-authentication-token`](../packages/host/authentication-token), [`host-authentication-desktop`](../packages/host/authentication-desktop) | [`client-connection`](../packages/client/connection) | - | Tries scope-owned credential verifiers in registration order and returns the first live Peer; transport source policy and business authorization stay with their consumers. | | `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Providers map remote and change request URLs, look up change requests by head branch, and read status in batches; watchers of one change request share one polling loop. | | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | A Session projection derives bindings from shell results and binding records and publishes their URLs without status to clients; push results trigger head-branch discovery, and Session watchers poll bound change requests through the forge registry. | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 3f33e41e82..a0febd2c93 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -38,6 +38,9 @@ flowchart LR svc_connection["ctx.connection
Authenticated browser transport"] pkg_api_gateway["api-gateway"] pkg_host_frontend_static["host-frontend-static"] + svc_connection_authentication["ctx.connection.authentication
Connection authentication provider registry"] + pkg_host_authentication_token["host-authentication-token"] + pkg_host_authentication_desktop["host-authentication-desktop"] pkg_experimental_forge["experimental-forge"] svc_forge["ctx.forge
Code host change requests"] pkg_experimental_forge_github["experimental-forge-github"] @@ -346,6 +349,7 @@ flowchart LR pkg_bash_sandbox --> svc_shell pkg_browser_use --> svc_browserUse pkg_client_connection --> svc_connection + pkg_client_connection --> svc_connection_authentication pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics @@ -392,6 +396,8 @@ flowchart LR pkg_goal --> svc_goals pkg_headless --> svc_headlessStartup pkg_hmr --> svc_hmr + pkg_host_authentication_desktop --> svc_connection_authentication + pkg_host_authentication_token --> svc_connection_authentication pkg_host_directory_picker --> svc_directoryPicker pkg_host_directory_picker_browse --> svc_directoryPicker pkg_host_directory_picker_native --> svc_directoryPicker @@ -516,6 +522,7 @@ flowchart LR svc_configEditor --> pkg_settings svc_connection --> pkg_api_gateway svc_connection --> pkg_host_frontend_static + svc_connection_authentication --> pkg_client_connection svc_cordisInspect --> pkg_tool_cordis svc_credentials --> pkg_api_settings_controller svc_credentials --> pkg_llm_deepseek @@ -669,7 +676,8 @@ flowchart LR | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | -| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | +| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 执行来源策略与共享 HTTP 请求分发;凭据验证归 ConnectionAuthentication,API 适配器注册端点和流。 | +| `ctx.connection.authentication` | `seam` | [`client-connection`](../packages/client/connection) | [`host-authentication-token`](../packages/host/authentication-token), [`host-authentication-desktop`](../packages/host/authentication-desktop) | [`client-connection`](../packages/client/connection) | - | 按注册顺序尝试作用域拥有的凭据验证器,返回首个存活 Peer;传输来源策略和业务授权仍归各自消费者。 | | `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | 提供方映射远端与变更请求 URL、按 head 分支查找变更请求并批量读取状态;同一变更请求的监听方共享一个轮询循环。 | | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Session 投影从 shell 结果与绑定记录派生绑定,并把不含状态的 URL 发布给客户端;推送结果触发按 head 分支的发现,Session 监听方通过 forge 注册表轮询已绑定的变更请求。 | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:使用 Session 权限进行的 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index bedb054293..ec47a2d8b3 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -222,7 +222,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-gateway` - `inject`: `typert` · `remoteAccess` -- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts) +- `source`: [`packages/api/gateway/src/index.ts:157`](../packages/api/gateway/src/index.ts) ```ts config-catalog /** Gateway transport configuration. */ @@ -497,8 +497,7 @@ export type Config = LocalConfig ## `@deepseek-ai/dsh-client-connection` -- `inject`: `credentials` -- `source`: [`packages/client/connection/src/index.ts:96`](../packages/client/connection/src/index.ts) +- `source`: [`packages/client/connection/src/index.ts:92`](../packages/client/connection/src/index.ts) ```ts config-catalog /** Browser authentication, request limits, and connection recovery configuration. */ @@ -512,8 +511,6 @@ export interface ConnectionConfig { * an entry here. A non-canonical or non-bare authority fails plugin load. */ trustedHosts?: string[] - /** Absolute browser and API cookie lifetime in days. Default: 30. */ - cookieMaxAgeDays?: number /** Maximum buffered JSON body for every `/api` request. Default: 300 MiB. */ maxRequestBodyBytes?: number } @@ -1783,6 +1780,40 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-host-authentication-desktop` + +- `inject`: `connection` · `connection.authentication` +- `source`: [`packages/host/authentication-desktop/src/index.ts:12`](../packages/host/authentication-desktop/src/index.ts) + +```ts config-catalog +/** In-memory startup input supplied by the Desktop process owner. */ +export interface Config { + /** Read the credential already validated on the private parent IPC channel. */ + readSecret: () => string +} +``` + + + + + +## `@deepseek-ai/dsh-host-authentication-token` + +- `inject`: `connection` · `connection.authentication` · `credentials` +- `source`: [`packages/host/authentication-token/src/index.ts:16`](../packages/host/authentication-token/src/index.ts) + +```ts config-catalog +/** Default browser and API cookie lifetime. */ +export interface Config { + /** Absolute cookie lifetime in days; default 30. */ + cookieMaxAgeDays: number +} +``` + + @@ -1821,8 +1852,8 @@ export interface Config { ## `@deepseek-ai/dsh-host-open-in-app` -- `inject`: `webServer` · `connection` · `subprocess` -- `source`: [`packages/host/open-in-app/src/index.ts:50`](../packages/host/open-in-app/src/index.ts) +- `inject`: `webServer` · `subprocess` +- `source`: [`packages/host/open-in-app/src/index.ts:46`](../packages/host/open-in-app/src/index.ts) ```ts config-catalog /** Open-in-app host configuration. */ @@ -1890,7 +1921,7 @@ export interface Config { ## `@deepseek-ai/dsh-host-webserver` -- `source`: [`packages/host/webserver/src/index.ts:97`](../packages/host/webserver/src/index.ts) +- `source`: [`packages/host/webserver/src/index.ts:171`](../packages/host/webserver/src/index.ts) ```ts config-catalog /** Web server listen, TLS, and response-compression config. */ @@ -4818,7 +4849,7 @@ export interface WebRuntimeConfig { export interface Config { /** Permit default-browser handoff after the Loader tree settles; an SSH launch suppresses it. */ openBrowser: boolean - /** Print the URL line on activation; a non-interactive layer can turn it off. */ + /** Print the URL lines on activation; a non-interactive layer can turn them off. */ printUrl: boolean /** * Register the `DSH_WEB_URL` bash variable naming this GUI. A one-shot diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index ba8a6e01ab..81de855b80 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -224,7 +224,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-gateway` - `inject`: `typert` · `remoteAccess` -- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts) +- `source`: [`packages/api/gateway/src/index.ts:157`](../packages/api/gateway/src/index.ts) ```ts config-catalog /** Gateway transport configuration. */ @@ -499,8 +499,7 @@ export type Config = LocalConfig ## `@deepseek-ai/dsh-client-connection` -- `inject`: `credentials` -- `source`: [`packages/client/connection/src/index.ts:96`](../packages/client/connection/src/index.ts) +- `source`: [`packages/client/connection/src/index.ts:92`](../packages/client/connection/src/index.ts) ```ts config-catalog /** Browser authentication, request limits, and connection recovery configuration. */ @@ -514,8 +513,6 @@ export interface ConnectionConfig { * an entry here. A non-canonical or non-bare authority fails plugin load. */ trustedHosts?: string[] - /** Absolute browser and API cookie lifetime in days. Default: 30. */ - cookieMaxAgeDays?: number /** Maximum buffered JSON body for every `/api` request. Default: 300 MiB. */ maxRequestBodyBytes?: number } @@ -1785,6 +1782,40 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-host-authentication-desktop` + +- `inject`: `connection` · `connection.authentication` +- `source`: [`packages/host/authentication-desktop/src/index.ts:12`](../packages/host/authentication-desktop/src/index.ts) + +```ts config-catalog +/** In-memory startup input supplied by the Desktop process owner. */ +export interface Config { + /** Read the credential already validated on the private parent IPC channel. */ + readSecret: () => string +} +``` + + + + + +## `@deepseek-ai/dsh-host-authentication-token` + +- `inject`: `connection` · `connection.authentication` · `credentials` +- `source`: [`packages/host/authentication-token/src/index.ts:16`](../packages/host/authentication-token/src/index.ts) + +```ts config-catalog +/** Default browser and API cookie lifetime. */ +export interface Config { + /** Absolute cookie lifetime in days; default 30. */ + cookieMaxAgeDays: number +} +``` + + @@ -1823,8 +1854,8 @@ export interface Config { ## `@deepseek-ai/dsh-host-open-in-app` -- `inject`: `webServer` · `connection` · `subprocess` -- `source`: [`packages/host/open-in-app/src/index.ts:50`](../packages/host/open-in-app/src/index.ts) +- `inject`: `webServer` · `subprocess` +- `source`: [`packages/host/open-in-app/src/index.ts:46`](../packages/host/open-in-app/src/index.ts) ```ts config-catalog /** Open-in-app host configuration. */ @@ -1892,7 +1923,7 @@ export interface Config { ## `@deepseek-ai/dsh-host-webserver` -- `source`: [`packages/host/webserver/src/index.ts:97`](../packages/host/webserver/src/index.ts) +- `source`: [`packages/host/webserver/src/index.ts:171`](../packages/host/webserver/src/index.ts) ```ts config-catalog /** Web server listen, TLS, and response-compression config. */ @@ -4820,7 +4851,7 @@ export interface WebRuntimeConfig { export interface Config { /** Permit default-browser handoff after the Loader tree settles; an SSH launch suppresses it. */ openBrowser: boolean - /** Print the URL line on activation; a non-interactive layer can turn it off. */ + /** Print the URL lines on activation; a non-interactive layer can turn them off. */ printUrl: boolean /** * Register the `DSH_WEB_URL` bash variable naming this GUI. A one-shot diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 1e32371657..39086ec5d9 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -33,7 +33,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | | `compaction/summary-error` | `waterfall` | [`packages/compaction/compaction/src/index.ts:106`](../packages/compaction/compaction/src/index.ts) | [`compaction-basic`](../packages/compaction/compaction-basic) (`waterfall`) | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | -| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:71`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | +| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:67`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | | `cordis/dynamic-package` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:383`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/dynamic-retract` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:389`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/inspect-query` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:395`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | @@ -92,7 +92,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | -| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:44`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | +| `webserver/authorize` | `bail` | [`packages/host/webserver/src/index.ts:60`](../packages/host/webserver/src/index.ts) | `webserver` (`bail`) | `connection` | +| `webserver/entry-url` | `emit` | [`packages/host/webserver/src/index.ts:53`](../packages/host/webserver/src/index.ts) | [`web-app`](../packages/bundle/web-app) (`emit`) | `authentication-token` | +| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:90`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | +| `webserver/request` | `waterfall` | [`packages/host/webserver/src/index.ts:68`](../packages/host/webserver/src/index.ts) | `webserver` (`waterfall`) | `authentication-token`, [`deepseek-account`](../packages/credentials/deepseek-account) | +| `webserver/upgrade` | `waterfall` | [`packages/host/webserver/src/index.ts:78`](../packages/host/webserver/src/index.ts) | `webserver` (`waterfall`) | `authentication-token` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:68`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:89`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 675cd96348..04012d0c65 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -35,7 +35,7 @@ | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | | `compaction/summary-error` | `waterfall` | [`packages/compaction/compaction/src/index.ts:106`](../packages/compaction/compaction/src/index.ts) | [`compaction-basic`](../packages/compaction/compaction-basic) (`waterfall`) | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | -| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:71`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | +| `connection/request` | `waterfall` | [`packages/client/connection/src/index.ts:67`](../packages/client/connection/src/index.ts) | `connection` (`waterfall`) | - | | `cordis/dynamic-package` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:383`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/dynamic-retract` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:389`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/inspect-query` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:395`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | @@ -94,7 +94,11 @@ | `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | -| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:44`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | +| `webserver/authorize` | `bail` | [`packages/host/webserver/src/index.ts:60`](../packages/host/webserver/src/index.ts) | `webserver` (`bail`) | `connection` | +| `webserver/entry-url` | `emit` | [`packages/host/webserver/src/index.ts:53`](../packages/host/webserver/src/index.ts) | [`web-app`](../packages/bundle/web-app) (`emit`) | `authentication-token` | +| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:90`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | +| `webserver/request` | `waterfall` | [`packages/host/webserver/src/index.ts:68`](../packages/host/webserver/src/index.ts) | `webserver` (`waterfall`) | `authentication-token`, [`deepseek-account`](../packages/credentials/deepseek-account) | +| `webserver/upgrade` | `waterfall` | [`packages/host/webserver/src/index.ts:78`](../packages/host/webserver/src/index.ts) | `webserver` (`waterfall`) | `authentication-token` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:68`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:89`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | diff --git a/docs/module-graph.md b/docs/module-graph.md index 6db1e26f10..3bb73c31f5 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -337,6 +337,8 @@ flowchart TD pkg_tool_call_timeout_policy["tool-call-timeout-policy"] end subgraph group_host["packages/host"] + pkg_host_authentication_desktop["host-authentication-desktop"] + pkg_host_authentication_token["host-authentication-token"] pkg_host_directory_picker["host-directory-picker"] pkg_host_directory_picker_auto["host-directory-picker-auto"] pkg_host_directory_picker_browse["host-directory-picker-browse"] @@ -534,6 +536,9 @@ flowchart TD pkg_experimental_webworker_runtime --> pkg_client_connection pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver + pkg_host_authentication_desktop --> pkg_client_connection + pkg_host_authentication_token --> pkg_client_connection + pkg_host_authentication_token --> pkg_host_webserver pkg_host_directory_picker_auto --> pkg_client_connection pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native @@ -1737,6 +1742,8 @@ flowchart TD | [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | +| [`host-authentication-desktop`](../packages/host/authentication-desktop) | `host` | [`client-connection`](../packages/client/connection) | +| [`host-authentication-token`](../packages/host/authentication-token) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`llm`](../packages/llm/llm) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 9e5b50ea90..dbfe20ba57 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -339,6 +339,8 @@ flowchart TD pkg_tool_call_timeout_policy["tool-call-timeout-policy"] end subgraph group_host["packages/host"] + pkg_host_authentication_desktop["host-authentication-desktop"] + pkg_host_authentication_token["host-authentication-token"] pkg_host_directory_picker["host-directory-picker"] pkg_host_directory_picker_auto["host-directory-picker-auto"] pkg_host_directory_picker_browse["host-directory-picker-browse"] @@ -536,6 +538,9 @@ flowchart TD pkg_experimental_webworker_runtime --> pkg_client_connection pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver + pkg_host_authentication_desktop --> pkg_client_connection + pkg_host_authentication_token --> pkg_client_connection + pkg_host_authentication_token --> pkg_host_webserver pkg_host_directory_picker_auto --> pkg_client_connection pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native @@ -1739,6 +1744,8 @@ flowchart TD | [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | +| [`host-authentication-desktop`](../packages/host/authentication-desktop) | `host` | [`client-connection`](../packages/client/connection) | +| [`host-authentication-token`](../packages/host/authentication-token) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`llm`](../packages/llm/llm) | diff --git a/docs/subsystems/web-server.i18n.yaml b/docs/subsystems/web-server.i18n.yaml index d34ca1303f..636e8c0c55 100644 --- a/docs/subsystems/web-server.i18n.yaml +++ b/docs/subsystems/web-server.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/web-server.md /http-server: - en: a4861c68f3eb0b03 - zh: a3da9f0467fdee02 + en: 6301c301934bb10e + zh: 2defa534b930f0b8 /http-server/routes: - en: 57adf92882ff0f77 - zh: d17992cca18cc790 + en: ccf0695b9a7b6366 + zh: 169ad948af43f881 /http-server/config: - en: 4b162bd9f280eb06 - zh: 3bea98dfee88c582 + en: 09c37ab771e95a9c + zh: d79927c7eb52e78e /http-server/the-service: - en: d1922a5e809e20c3 - zh: 5c1772c81a19784c + en: 2173f75581032b02 + zh: 854c41d589c119ef diff --git a/docs/subsystems/web-server.md b/docs/subsystems/web-server.md index 2420b6713b..dd23678689 100644 --- a/docs/subsystems/web-server.md +++ b/docs/subsystems/web-server.md @@ -2,7 +2,7 @@ English | [中文](web-server.zh.md) -[dsh-host-webserver](../../packages/host/webserver) is the browser HTTP carrier for the GUI host: one `node:http` server — `node:https` when `tls` is configured — providing `ctx.webServer`, a named-route registry, optional gzip response compression, index.html transform callbacks, and one fallback, a handler or a resource, that a plugin may claim. It is not part of the agent loop and not a capability seam; its only harness concept is the Peer an index render speaks for, and another plugin registers every feature route, including the `/api` bridge, plugin bundles, and the HMR event stream ([layering reference](../../packages/boot/app-boot/README.md)). It serves browsers only: Electron loads the built files over `file://` and sends fetch requests through an IPC bridge instead of this server. +[dsh-host-webserver](../../packages/host/webserver) provides the GUI Host's HTTP or TLS listener, route matching and admission, optional gzip, index rendering, and one fallback. Feature plugins register their own routes; Connection supplies source and credential decisions through `webserver/authorize`. The carrier passes each admitted Peer directly to the handler or resource rather than constructing a request-context container ([layering reference](../../packages/boot/app-boot/README.md)). Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) @@ -20,14 +20,16 @@ interface WebRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */ - handler: (req: IncomingMessage, res: ServerResponse) => void | Promise + handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } ``` ```ts type-equiv /** - * Answers one GET or HEAD request with a Fetch response. An HTTP request - * arrives without a Peer and carries the client's headers; an in-process + * Answers one GET or HEAD request with a Fetch response and its admitted Peer. + * Anonymous HTTP admission may omit the Peer; an in-process * {@link WebServer.readResource} read passes the Peer its caller admitted. */ type WebResource = (request: Request, peer?: PeerScope) => Promise @@ -41,12 +43,22 @@ interface WebResourceRoute { path: string /** Answers HTTP GET and HEAD requests and in-process reads. */ resource: WebResource + /** Defaults to required; in-process reads still enforce deny. */ + auth?: WebAuthenticationRule } ``` -Match order is fixed: exact table first, then longest matching prefix, then the registered fallback. Registration order carries no request-facing semantics — named routes are composed to be disjoint, and the fallback seat answers anything no named route claims; one owner only, a second registration throws. The shipped Web composition claims the seat with [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts), the SPA dist server with locked semantics: Connection authenticates the dist root and configured index before their HTML is read; non-index assets remain public; non-GET/HEAD is 405, traversal outside the dist root is 403, existing files are served directly, absent or non-file targets are empty 404 responses, and unknown extensions ship as octet-stream. +All `webserver/*` events use the corresponding WebServer as their dispatch subject, including `index-inject` and `entry-url`. Ordinary listeners match the emitter's `webServer` isolation; explicit `{ global: true }` listeners bypass that filter. Passing a Peer as event data does not select listeners. Custom carriers and application emitters must supply the WebServer subject. -A route or the fallback may give a resource, a function from a Fetch `Request` to a `Response`, instead of a handler. HTTP `GET` and `HEAD` requests reach it without a Peer, and `readResource(request, peer)` reads it in process for the Peer its caller admitted; a read follows the same match order but reaches only resources, so a route that returns owner-private data or performs an action stays a handler even when it answers `GET`. +Match order is exact, longest prefix, then the single-owner fallback; upgrades match exact paths. After matching, `auth` resolves to `anonymous`, `required` (default), or `deny`, either directly or through a synchronous request selector. `deny` returns 403 without an authorization event. Other policies emit synchronous `webserver/authorize`; the first decision wins. Without a decision, `anonymous` allows and `required` returns 503. Connection checks sources for both and calls ConnectionAuthentication only for authenticated routes. Anonymous assets are therefore credential-free, not exempt from active Connection source policy. + +Handlers receive the admitted Peer as their trailing parameter; resources receive it through the existing `resource(request, peer?)` argument. Authenticated routes require a live Peer; anonymous routes may omit it. After admission, resources accept only GET/HEAD. Trusted `readResource(request, peer)` follows the same match order and reaches only resources, bypassing source and credential checks but still returning 403 for a resolved `deny`. The [frontend fallback](../../packages/host/frontend-static/README.md) selects authenticated index access and anonymous static assets, then renders index startup data for the supplied Peer. + +`webserver/request(request, response, next)` remains an HTTP waterfall before route selection and admission; a listener owns the response or awaits `next()`. The [Token plugin](../../packages/host/authentication-token/README.md) uses it for root Token exchange and registers `/connect` with anonymous auth, verifying the launch token after Connection source checks. Page resources consume their admitted Peer without repeating authentication. + +After successful upgrade admission, `webserver/upgrade(req, socket, head, peer, next)` runs before the registered protocol handler. It carries the admitted Peer, or `undefined` for anonymous access; denied requests never enter it. Listeners handle the Socket or await `next()`; the fallback awaits the route handler, including asynchronous completion. Middleware or handler failures are logged and destroy the Socket. On `/api/remote.mux`, Token applies single-Socket ownership and credential revocation only to API Peers in its own map; other Providers delegate without Token policy. + +`webserver/entry-url(baseUrl, entries)` synchronously collects complete entry URLs for a supplied server base URL as `WebEntryUrl` records with `label`, complete `url`, and boolean `open`. WebApp emits it after Loader settlement and startup audit, prints each entry when configured, and opens only the first eligible entry outside SSH. An empty list produces neither output nor opening. Token contributes its signed URL without reading WebApp services; public-address configuration remains in WebApp. @@ -99,13 +111,15 @@ interface TlsConfig { } ``` -No composition can bind every interface at once: the unspecified address is rejected at load. The exported `isWildcardHost` and `isLoopbackHost` classify a bind address from its parsed value, and an IPv6 `%zone` is kept for `listen` while classification reads the address alone. The carrier owns no authentication or Origin policy, and it serves plain HTTP unless `tls` supplies a certificate and key. `compression` defaults to `none`; the shipped Web bundle selects gzip level 1 with a 1024-byte threshold. The shipped `dsh web` command selects loopback by default and accepts one concrete `--host` address, warning at startup when a non-loopback bind serves plain HTTP; its Connection plugin supplies Host/Origin checks plus browser-session authentication for every Host API route and stream, and the bind address plus `--trusted-host` govern which browser Host is accepted; `--public-url` changes only the advertised URL. Other compositions own their bind and route-authentication policy. The dist location is an assembly fact of the frontend plugin that claims the seat. +No composition can bind every interface at once: the unspecified address is rejected at load. The exported `isWildcardHost` and `isLoopbackHost` classify a bind address from its parsed value, and an IPv6 `%zone` is kept for `listen` while classification reads the address alone. The carrier enforces route auth declarations; Connection owns source checks and ConnectionAuthentication owns credential verification. It serves plain HTTP unless `tls` supplies a certificate and key. `compression` defaults to `none`; the shipped Web bundle selects gzip level 1 with a 1024-byte threshold. The shipped `dsh web` command selects loopback by default and accepts one concrete `--host` address, warning at startup when a non-loopback bind serves plain HTTP; its Connection plugin checks Host/Origin on matched anonymous and authenticated routes and verifies credentials where authentication is required, and the bind address plus `--trusted-host` govern which browser Host is accepted; `--public-url` changes only the advertised URL. Other compositions own their bind and route-authentication policy. The dist location is an assembly fact of the frontend plugin that claims the seat. ## The service +The nested `connection.authentication` service selects a Peer through registered Providers; Connection applies source policy and WebServer passes the selected Peer to each call. The [Token plugin](../../packages/host/authentication-token/README.md) contributes its signed login URL; WebApp owns startup printing and browser opening. [Desktop](../../apps/desktop/README.md#application-overview) registers a separate Provider using a credential delivered over its private parent–Host IPC channel; its ready message carries the ordinary Host address and startup injections. + `WebServer` (`ctx.webServer`) listens immediately on activation; a listen failure (EADDRINUSE…) rejects initialization, and the boot process reports the failed fiber. The `tls` pair is read once before the listener binds, and an unreadable, empty, or mismatched pair rejects initialization the same way instead of falling back to HTTP. `register(route)` adds one named route and returns its disposer; a duplicate `(kind, path)` throws because route patterns are a composition-level contract and a collision is a misconfiguration. Gzip wraps eligible socket-backed responses inside the server, so handlers keep direct `ServerResponse` ownership, and a resource hands the service a `Response` to write back. Existing content encodings, `Cache-Control: no-transform`, ranges, SSE, ZIP, and the packaged `.gz` Worker image remain identity responses. `collectIndexInjections(peer)` gathers structured `IndexInjection` rows over one `webserver/index-inject` emit that passes the Peer the page speaks for, and `renderIndex(html, peer)` renders them into successful root and configured index responses before applying the raw `tapIndex(transform)` escape-hatch transforms in registration order; [dsh-client-modules](../../packages/client/modules) answers the event with the boot manifest rows. `port` reads the listening port, including the port assigned by the OS when `config.port` is 0, and `protocol` reports the scheme the listener serves (`http:` or `https:`). -A request whose handling throws (a malformed %-escape hitting `decodeURIComponent`, a client dropping mid-body) is logged as a warning and answered 400 — or the socket destroyed when headers are already out — never a process exit. Disposal pairs `close()` with `closeAllConnections()` because a handler may hold its response open (SSE) and such connections never end on their own; without the force-close, teardown would hang. A TLS socket counts as a connection only after its handshake, so the server tracks raw TLS sockets beside upgraded ones and destroys both at disposal. The package never prints: the URL line belongs to the shell. Per-package operational detail, including the dev-mode bundle watch pipeline, stays in the [README](../../packages/host/webserver/README.md). +A request whose handling throws (a malformed %-escape hitting `decodeURIComponent`, a client dropping mid-body) is logged as a warning and answered 400 — or the socket destroyed when headers are already out — never a process exit. Disposal pairs `close()` with `closeAllConnections()` because a handler may hold its response open (SSE) and such connections never end on their own; without the force-close, teardown would hang. A TLS socket counts as a connection only after its handshake, so the server tracks raw TLS sockets beside upgraded ones and destroys both at disposal. WebApp owns entry-URL printing and browser opening; this server owns HTTP delivery. Per-package operational detail, including the dev-mode bundle watch pipeline, stays in the [README](../../packages/host/webserver/README.md). @@ -130,15 +144,7 @@ Host `ctx.connection` members consumed by transport-independent adapters. createSharedFetchHandler(channel: '/api'): ConnectionFetchHandler /** - * Apply Connection's Host/Origin checks and browser authentication to - * another Web route. - * @param request - request headers from the HTTP or upgrade request. - * @returns rejection status, or undefined when the route may accept the request. - */ -requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection - -/** - * Admit an HTTP request against its signed browser or API credential and live Peer. + * Apply Host/Origin checks and admit the first live Peer returned by a registered credential verifier. * @param request - request headers from the HTTP or upgrade request. * @returns the credential's Peer, or the rejection status. */ @@ -146,42 +152,42 @@ admit(request: ConnectionTrustRequest): PeerAdmission /** * Create an independent in-process Peer, disposed with the Context that read `ctx.connection`. - * @param options - fixed principal and optional interaction participation (default `answer`). + * @param options - fixed principal and interaction participation (default answer). * @returns a new Peer distinct from every other Peer. */ createPeer(options: { readonly principal: Principal; readonly interactions?: 'answer' | 'none' }): PeerScope - -/** - * Claim a physical socket for an API Peer; browser sockets share their owner Peer. - * @param request - authenticated upgrade request headers. - * @returns the Peer and idempotent release, or 409 for duplicate API ownership. - * The carrier releases on socket termination or failed upgrade; release removes - * API admission synchronously without cancelling independent HTTP calls. - */ -admitConnection(request: ConnectionTrustRequest): ConnectionAdmission - -/** - * Authenticate one frontend index request, owning a token redirect or 401. - * The cookie this mints is `Secure` when the mounted Web carrier serves TLS, - * which only that listener's protocol decides. - * @param request - root or configured-index HTTP request. - * @param response - response owned when the result is false. - * @returns true only when the frontend may serve index.html. - */ -authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean - -/** - * Add the fresh process token to an ordinary Web application URL. - * @param baseUrl - clean application URL whose authority and mount are preserved. - * @returns tokenized URL for initial login; a mount proxy strips its prefix before {@link authorizeIndex}. - */ -authenticatedUrl(baseUrl: string): string ``` Types: [Principal](typert.md) Source: [`packages/client/connection/src/rpc.ts`](../../packages/client/connection/src/rpc.ts) + + +### `ctx.connection.authentication` — `ConnectionAuthentication` + +Credential verifier registry whose registrations belong to the calling plugin. + +```ts cordis-catalog +/** + * Add a credential verifier after the existing registrations. + * @param provider - verifier owning its credential and Peer selection. + * @returns disposer withdrawing this registration; the calling scope also withdraws it on unload. + */ +register(provider: AuthenticationProvider): () => Promise + +/** + * Verify credentials without applying an HTTP response or source policy. + * @param request - current carrier headers and cancellation facts. + * @returns the first live Peer, 401 if no provider accepts, or 503 when verification failed without success. + */ +authenticate(request: ConnectionTrustRequest): PeerAdmission +``` + +Types: [AuthenticationProvider](../../packages/client/connection/README.md#browser-authentication-and-request-trust) + +Source: [`packages/client/connection/src/authentication.ts`](../../packages/client/connection/src/authentication.ts) + ### `ctx.webApp` — `WebApp` @@ -202,7 +208,7 @@ Source: [`packages/bundle/web-app/src/index.ts`](../../packages/bundle/web-app/s ### `ctx.webServer` — `WebServer` -The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and a request no named route matches is answered 404 until the fallback owner registers. +The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and a request no named route matches is answered 404 until the fallback owner registers. HTTP and upgrade admission refusals carry `Cache-Control: no-store`. ```ts cordis-catalog /** @@ -235,10 +241,10 @@ registerUpgrade(route: WebUpgradeRoute): () => void * composition). One owner only — a second registration throws, because two * fallbacks cannot compose. * @param fallback - a handler owning the full response lifecycle of - * unmatched requests, or `{ resource }` answering them. + * unmatched requests, or an object declaring `handler` or `resource` and auth. * @returns the disposer releasing the seat. */ -registerFallback(fallback: WebRoute['handler'] | Pick): () => void +registerFallback(fallback: WebRoute['handler'] | WebFallback): () => void /** * Read the response an HTTP request for the same URL would receive, as the @@ -246,6 +252,7 @@ registerFallback(fallback: WebRoute['handler'] | Pick + +#### `webserver/authorize` — bail + +Admit a matched request synchronously; the first decision wins. + +```ts cordis-catalog +/** + * Admit a matched request synchronously; the first decision wins. + * @param request - headers, target, transport, and available cancellation state. + * @param policy - resolved route policy; deny never emits this event. + * @mode bail + */ +'webserver/authorize'(request: WebAuthRequest, policy: WebAuthPolicy): WebAdmission | undefined +``` + +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + + + +#### `webserver/entry-url` — emit + +Collect complete entry URLs for an advertised server address. + +```ts cordis-catalog +/** + * Collect complete entry URLs for an advertised server address. + * @param baseUrl - advertised server base URL without provider credentials. + * @param entries - entries appended synchronously in listener order. + * @mode emit + */ +'webserver/entry-url'(baseUrl: string, entries: WebEntryUrl[]): void +``` + +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + #### `webserver/index-inject` — emit @@ -343,5 +386,45 @@ Collect the structured index injection table for the page `peer` speaks for. Emi 'webserver/index-inject'(table: IndexInjection[], peer: PeerScope): void ``` +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + + + +#### `webserver/request` — waterfall + +Handle an HTTP request before named-route and fallback dispatch. + +```ts cordis-catalog +/** + * Handle an HTTP request before named-route and fallback dispatch. + * @param request - original incoming HTTP request. + * @param response - response owned by the listener or its delegated handler. + * @param next - dispatch to the next listener or the matching route. + * @mode waterfall + */ +'webserver/request'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise +``` + +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + + + +#### `webserver/upgrade` — waterfall + +Handle an admitted upgrade before its registered protocol handler. + +```ts cordis-catalog +/** + * Handle an admitted upgrade before its registered protocol handler. + * @param request - original upgrade request. + * @param socket - transport owned by the upgrade. + * @param head - bytes received after the HTTP headers. + * @param peer - authenticated identity, absent for anonymous admission. + * @param next - delegate to the next listener or protocol handler. + * @mode waterfall + */ +'webserver/upgrade'( request: IncomingMessage, socket: Duplex, head: Buffer, peer: PeerScope | undefined, next: () => Promise, ): Promise +``` + Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) diff --git a/docs/subsystems/web-server.zh.md b/docs/subsystems/web-server.zh.md index a59344ad75..07bad3ba6e 100644 --- a/docs/subsystems/web-server.zh.md +++ b/docs/subsystems/web-server.zh.md @@ -2,7 +2,7 @@ [English](web-server.md) | 中文 -[dsh-host-webserver](../../packages/host/webserver) 是 GUI Host 的浏览器 HTTP 载体:一个 `node:http` 服务器——配置 `tls` 时改用 `node:https`——提供 `ctx.webServer`、具名路由注册表、可选的 gzip 响应压缩、index.html 转换回调,以及一个可由插件认领的回退(handler 或 resource)。它不属于 agent loop(智能体循环),也不是能力 seam;它唯一涉及的 harness 概念是 index 渲染所代表的 Peer。其他插件负责注册所有功能路由,包括 `/api` 桥接、插件 bundle 和 HMR(热模块替换)事件流([分层说明](../../packages/boot/app-boot/README.zh.md))。该服务器只服务浏览器:Electron 通过 `file://` 加载已构建文件,并经 IPC 桥接发送 fetch 请求,不使用本服务器。 +[dsh-host-webserver](../../packages/host/webserver) 提供 GUI Host 的 HTTP 或 TLS 监听、路由匹配与准入、可选 gzip、index 渲染及唯一回退。功能插件注册各自路由;Connection 通过 `webserver/authorize` 提供来源与凭据决策。载体直接向 handler 或 resource 传递准入 Peer,不构造请求上下文容器([分层说明](../../packages/boot/app-boot/README.zh.md))。 源码:[`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) @@ -20,14 +20,16 @@ interface WebRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */ - handler: (req: IncomingMessage, res: ServerResponse) => void | Promise + handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } ``` ```ts type-equiv /** - * Answers one GET or HEAD request with a Fetch response. An HTTP request - * arrives without a Peer and carries the client's headers; an in-process + * Answers one GET or HEAD request with a Fetch response and its admitted Peer. + * Anonymous HTTP admission may omit the Peer; an in-process * {@link WebServer.readResource} read passes the Peer its caller admitted. */ type WebResource = (request: Request, peer?: PeerScope) => Promise @@ -41,12 +43,22 @@ interface WebResourceRoute { path: string /** Answers HTTP GET and HEAD requests and in-process reads. */ resource: WebResource + /** Defaults to required; in-process reads still enforce deny. */ + auth?: WebAuthenticationRule } ``` -匹配顺序固定:先查 exact 表,再取最长匹配前缀,最后落到已注册的回退。注册顺序不携带任何面向请求的语义:具名路由在组合上互不相交,任何未被具名路由认领的请求都由回退席位应答;席位只有一个所有者,第二次注册会抛出异常。发布的 Web 组合用 [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts) 认领席位,即遵循固定语义的 SPA dist 服务器:Connection 在读取 dist 根目录和配置 index 的 HTML 前完成认证;非 index 资产保持公开;非 GET/HEAD 返回 405,越出 dist 根目录的遍历返回 403,现有文件直接提供,缺失或不是文件的目标返回空的 404,未知扩展名按 octet-stream 发送。 +所有 `webserver/*` 事件均以对应的 WebServer 为分发 subject,包括 `index-inject` 与 `entry-url`。普通监听器匹配发起者的 `webServer` isolation;显式 `{ global: true }` 监听器跳过该过滤。作为事件数据传入的 Peer 不决定监听器选择。自定义载体和应用发起者必须提供 WebServer subject。 -路由或回退可以用 resource——一个把 Fetch `Request` 映射为 `Response` 的函数——代替 handler。HTTP 的 `GET`、`HEAD` 请求不带 Peer 到达它,`readResource(request, peer)` 则在进程内按调用方准入的 Peer 读取它;读取遵循同样的匹配顺序但只到达 resource,因此返回 owner 私有数据或会执行操作的路由即使应答 `GET` 也保持为 handler。 +匹配顺序为精确、最长前缀、唯一 owner 的回退;upgrade 精确匹配。匹配后,`auth` 直接或通过同步请求选择器解析为 `anonymous`、`required`(默认)或 `deny`。`deny` 不触发准入事件,直接返回403。其余策略触发同步 `webserver/authorize` 并采用首个决策;无人决策时匿名放行,认证返回503。Connection 对两者均检查来源,仅对认证路由调用 ConnectionAuthentication。因此匿名资源免凭据,但不能免除活动 Connection 的来源策略。 + +handler 通过末尾参数取得准入 Peer,resource 使用已有 `resource(request, peer?)` 参数。认证路由必须取得存活 Peer,匿名路由可省略。准入后 resource 只接受 GET/HEAD。可信 `readResource(request, peer)` 遵循同样的匹配顺序且仅访问 resource,跳过来源与凭据检查,但解析出的 `deny` 仍返回403。[前端回退](../../packages/host/frontend-static/README.zh.md)选择 index 认证访问与静态资源匿名访问,再为传入 Peer 渲染 index 启动数据。 + +`webserver/request(request, response, next)` 保持为路由选择与准入前的 HTTP waterfall;监听器拥有响应或等待 `next()`。[Token 插件](../../packages/host/authentication-token/README.zh.md)通过它处理根 Token 交换,并以匿名 auth 注册 `/connect`,在 Connection 来源检查后验证启动 Token。页面 resource 使用准入 Peer,不重复认证。 + +upgrade 准入成功后,`webserver/upgrade(req, socket, head, peer, next)` 在已注册协议 handler 前执行。它携带准入 Peer,匿名访问可为 `undefined`;被拒绝的请求不会进入。监听器自行处理 Socket 或等待 `next()`;waterfall 的末端等待路由 handler,包括其异步完成。中间件或 handler 失败时记录日志并销毁 Socket。在 `/api/remote.mux` 上,Token 仅对自己映射表内的 API Peer 执行单 Socket 所有权与凭据撤销;其他 Provider 委派后续处理,不应用 Token 策略。 + +`webserver/entry-url(baseUrl, entries)` 根据传入的服务器基地址同步收集完整入口 URL,以 `WebEntryUrl` 记录表示,字段为 `label`、完整 `url` 与布尔值 `open`。WebApp 在 Loader 装配结束并完成启动检查后触发,按配置逐行打印,并仅在非 SSH 下打开首个允许自动打开的入口。空列表不产生输出或打开动作。Token 无需读取 WebApp 服务即可贡献签名 URL;公开地址配置仍归 WebApp。 @@ -99,13 +111,15 @@ interface TlsConfig { } ``` -没有组合能一次性绑定所有网络接口:未指定地址在加载时即被拒绝。导出的 `isWildcardHost` 与 `isLoopbackHost` 按解析后的地址值分类,IPv6 的 `%zone` 会保留给 `listen`,而分类只读取地址本身。载体不拥有认证或 Origin 策略,并且除非 `tls` 提供证书与密钥,否则以明文 HTTP 提供服务。`compression` 默认为 `none`;随附的 Web 组合选择 gzip level 1 和 1024 字节阈值。随附的 `dsh web` 命令默认选择 loopback 并接受一个具体的 `--host` 地址,非 loopback 绑定以明文 HTTP 提供服务时会在启动时警告;其 Connection 插件为每个 Host API route 与 stream 提供 Host/Origin 校验和浏览器会话认证,绑定地址加 `--trusted-host` 决定接受哪个浏览器 Host;`--public-url` 只改变公告的 URL。其他组合自行拥有绑定与路由认证策略。dist 位置是认领席位的前端插件的组装事实。 +没有组合能一次性绑定所有网络接口:未指定地址在加载时即被拒绝。导出的 `isWildcardHost` 与 `isLoopbackHost` 按解析后的地址值分类,IPv6 的 `%zone` 会保留给 `listen`,而分类只读取地址本身。载体执行路由 auth 声明;Connection 拥有来源检查,ConnectionAuthentication 拥有凭据验证;除非 `tls` 提供证书与密钥,否则以明文 HTTP 提供服务。`compression` 默认为 `none`;随附的 Web 组合选择 gzip level 1 和 1024 字节阈值。随附的 `dsh web` 命令默认选择 loopback 并接受一个具体的 `--host` 地址,非 loopback 绑定以明文 HTTP 提供服务时会在启动时警告;其 Connection 插件对匹配的匿名与认证路由检查 Host/Origin,并在要求认证时验证凭据,绑定地址加 `--trusted-host` 决定接受哪个浏览器 Host;`--public-url` 只改变公告的 URL。其他组合自行拥有绑定与路由认证策略。dist 位置是认领席位的前端插件的组装事实。 ## 服务 +嵌套服务 `connection.authentication` 通过注册的 Provider 选择 Peer;Connection 执行来源策略,WebServer 将选定 Peer 传给各次调用。[Token 插件](../../packages/host/authentication-token/README.zh.md)贡献签名登录 URL;WebApp 拥有启动打印和浏览器打开行为。[Desktop](../../apps/desktop/README.zh.md#application-overview)使用父进程与 Host 之间私有 IPC 通道交付的凭据,注册独立 Provider;其 ready 消息携带普通 Host 地址和启动注入。 + `WebServer`(`ctx.webServer`)在激活时立即监听;监听失败(EADDRINUSE 等)会使初始化被拒绝,启动进程会报告失败的 fiber。`tls` 证书对在监听器绑定前读取一次;文件不可读、为空或二者不匹配时同样会使初始化被拒绝,而不是回退到 HTTP。`register(route)` 添加一条具名路由并返回其 disposer;重复的 `(kind, path)` 抛出异常,因为路由模式是组合层约定,冲突即配置错误。Gzip 在服务器内部包装符合条件且基于 socket 的响应,因此 handler 继续直接持有 `ServerResponse`,resource 则把 `Response` 交给服务写回。已有内容编码、`Cache-Control: no-transform`、范围响应、SSE、ZIP 与打包后的 `.gz` Worker 镜像均保持 identity 响应。`collectIndexInjections(peer)` 经一次传入页面所代表 Peer 的 `webserver/index-inject` emit 收集结构化 `IndexInjection` 行,`renderIndex(html, peer)` 把它们渲染进成功的根路径和配置 index 响应,随后再按注册顺序应用原始的 `tapIndex(transform)` 逃生口转换;[dsh-client-modules](../../packages/client/modules) 以启动 manifest(元数据清单)行回应该事件。`port` 读取监听端口,包括 `config.port` 为 0 时操作系统分配的端口,`protocol` 则报告监听器提供的协议(`http:` 或 `https:`)。 -处理过程中抛出异常的请求(畸形的 % 转义撞上 `decodeURIComponent`、客户端在请求体中途断开)会记录为警告并应答 400(响应头已发出时则销毁 socket),绝不导致进程退出。dispose(资源释放)把 `close()` 与 `closeAllConnections()` 配对使用,因为处理器可能像 SSE(Server-Sent Events)那样保持响应打开,而这类连接永远不会自行结束;没有强制关闭,拆卸就会挂起。TLS socket 只有完成握手后才计入连接,因此服务器会把原始 TLS socket 与升级后的 socket 一并跟踪,并在 dispose 时销毁两者。该包从不打印输出:URL 行归 shell 所有。逐包运维细节(含开发模式的 bundle 监视流水线)留在 [README](../../packages/host/webserver/README.zh.md) 中。 +处理过程中抛出异常的请求(畸形的 % 转义撞上 `decodeURIComponent`、客户端在请求体中途断开)会记录为警告并应答 400(响应头已发出时则销毁 socket),绝不导致进程退出。dispose(资源释放)把 `close()` 与 `closeAllConnections()` 配对使用,因为处理器可能像 SSE(Server-Sent Events)那样保持响应打开,而这类连接永远不会自行结束;没有强制关闭,拆卸就会挂起。TLS socket 只有完成握手后才计入连接,因此服务器会把原始 TLS socket 与升级后的 socket 一并跟踪,并在 dispose 时销毁两者。WebApp 拥有入口 URL 的打印和浏览器打开行为,本服务器负责 HTTP 交付。逐包运维细节(含开发模式的 bundle 监视流水线)留在 [README](../../packages/host/webserver/README.zh.md) 中。 @@ -130,15 +144,7 @@ Host `ctx.connection` members consumed by transport-independent adapters. createSharedFetchHandler(channel: '/api'): ConnectionFetchHandler /** - * Apply Connection's Host/Origin checks and browser authentication to - * another Web route. - * @param request - request headers from the HTTP or upgrade request. - * @returns rejection status, or undefined when the route may accept the request. - */ -requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection - -/** - * Admit an HTTP request against its signed browser or API credential and live Peer. + * Apply Host/Origin checks and admit the first live Peer returned by a registered credential verifier. * @param request - request headers from the HTTP or upgrade request. * @returns the credential's Peer, or the rejection status. */ @@ -146,42 +152,42 @@ admit(request: ConnectionTrustRequest): PeerAdmission /** * Create an independent in-process Peer, disposed with the Context that read `ctx.connection`. - * @param options - fixed principal and optional interaction participation (default `answer`). + * @param options - fixed principal and interaction participation (default answer). * @returns a new Peer distinct from every other Peer. */ createPeer(options: { readonly principal: Principal; readonly interactions?: 'answer' | 'none' }): PeerScope - -/** - * Claim a physical socket for an API Peer; browser sockets share their owner Peer. - * @param request - authenticated upgrade request headers. - * @returns the Peer and idempotent release, or 409 for duplicate API ownership. - * The carrier releases on socket termination or failed upgrade; release removes - * API admission synchronously without cancelling independent HTTP calls. - */ -admitConnection(request: ConnectionTrustRequest): ConnectionAdmission - -/** - * Authenticate one frontend index request, owning a token redirect or 401. - * The cookie this mints is `Secure` when the mounted Web carrier serves TLS, - * which only that listener's protocol decides. - * @param request - root or configured-index HTTP request. - * @param response - response owned when the result is false. - * @returns true only when the frontend may serve index.html. - */ -authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean - -/** - * Add the fresh process token to an ordinary Web application URL. - * @param baseUrl - clean application URL whose authority and mount are preserved. - * @returns tokenized URL for initial login; a mount proxy strips its prefix before {@link authorizeIndex}. - */ -authenticatedUrl(baseUrl: string): string ``` Types: [Principal](typert.zh.md) Source: [`packages/client/connection/src/rpc.ts`](../../packages/client/connection/src/rpc.ts) + + +### `ctx.connection.authentication` — `ConnectionAuthentication` + +Credential verifier registry whose registrations belong to the calling plugin. + +```ts cordis-catalog +/** + * Add a credential verifier after the existing registrations. + * @param provider - verifier owning its credential and Peer selection. + * @returns disposer withdrawing this registration; the calling scope also withdraws it on unload. + */ +register(provider: AuthenticationProvider): () => Promise + +/** + * Verify credentials without applying an HTTP response or source policy. + * @param request - current carrier headers and cancellation facts. + * @returns the first live Peer, 401 if no provider accepts, or 503 when verification failed without success. + */ +authenticate(request: ConnectionTrustRequest): PeerAdmission +``` + +Types: [AuthenticationProvider](../../packages/client/connection/README.zh.md#browser-authentication-and-request-trust) + +Source: [`packages/client/connection/src/authentication.ts`](../../packages/client/connection/src/authentication.ts) + ### `ctx.webApp` — `WebApp` @@ -202,7 +208,7 @@ Source: [`packages/bundle/web-app/src/index.ts`](../../packages/bundle/web-app/s ### `ctx.webServer` — `WebServer` -The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and a request no named route matches is answered 404 until the fallback owner registers. +The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and a request no named route matches is answered 404 until the fallback owner registers. HTTP and upgrade admission refusals carry `Cache-Control: no-store`. ```ts cordis-catalog /** @@ -235,10 +241,10 @@ registerUpgrade(route: WebUpgradeRoute): () => void * composition). One owner only — a second registration throws, because two * fallbacks cannot compose. * @param fallback - a handler owning the full response lifecycle of - * unmatched requests, or `{ resource }` answering them. + * unmatched requests, or an object declaring `handler` or `resource` and auth. * @returns the disposer releasing the seat. */ -registerFallback(fallback: WebRoute['handler'] | Pick): () => void +registerFallback(fallback: WebRoute['handler'] | WebFallback): () => void /** * Read the response an HTTP request for the same URL would receive, as the @@ -246,6 +252,7 @@ registerFallback(fallback: WebRoute['handler'] | Pick + +#### `webserver/authorize` — bail + +Admit a matched request synchronously; the first decision wins. + +```ts cordis-catalog +/** + * Admit a matched request synchronously; the first decision wins. + * @param request - headers, target, transport, and available cancellation state. + * @param policy - resolved route policy; deny never emits this event. + * @mode bail + */ +'webserver/authorize'(request: WebAuthRequest, policy: WebAuthPolicy): WebAdmission | undefined +``` + +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + + + +#### `webserver/entry-url` — emit + +Collect complete entry URLs for an advertised server address. + +```ts cordis-catalog +/** + * Collect complete entry URLs for an advertised server address. + * @param baseUrl - advertised server base URL without provider credentials. + * @param entries - entries appended synchronously in listener order. + * @mode emit + */ +'webserver/entry-url'(baseUrl: string, entries: WebEntryUrl[]): void +``` + +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + #### `webserver/index-inject` — emit @@ -343,5 +386,45 @@ Collect the structured index injection table for the page `peer` speaks for. Emi 'webserver/index-inject'(table: IndexInjection[], peer: PeerScope): void ``` +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + + + +#### `webserver/request` — waterfall + +Handle an HTTP request before named-route and fallback dispatch. + +```ts cordis-catalog +/** + * Handle an HTTP request before named-route and fallback dispatch. + * @param request - original incoming HTTP request. + * @param response - response owned by the listener or its delegated handler. + * @param next - dispatch to the next listener or the matching route. + * @mode waterfall + */ +'webserver/request'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise +``` + +Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) + + + +#### `webserver/upgrade` — waterfall + +Handle an admitted upgrade before its registered protocol handler. + +```ts cordis-catalog +/** + * Handle an admitted upgrade before its registered protocol handler. + * @param request - original upgrade request. + * @param socket - transport owned by the upgrade. + * @param head - bytes received after the HTTP headers. + * @param peer - authenticated identity, absent for anonymous admission. + * @param next - delegate to the next listener or protocol handler. + * @mode waterfall + */ +'webserver/upgrade'( request: IncomingMessage, socket: Duplex, head: Buffer, peer: PeerScope | undefined, next: () => Promise, ): Promise +``` + Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts) diff --git a/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.i18n.yaml new file mode 100644 index 0000000000..b6295c8463 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md +/: + en: 10a66c5161e99e35 + zh: aa3f7c01150e06ef +/token-provider-and-route-admission-migration: + en: d8b41387fdc1a75e + zh: 0cc6b49d0a9ab47d +/token-provider-and-route-admission-migration/change: + en: 2eb6e67f4c5e7f94 + zh: 7598b32279c00ab7 +/token-provider-and-route-admission-migration/migration: + en: 02e2f80dbbedfe0b + zh: f21bd866777dd3f3 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md new file mode 100644 index 0000000000..06d8916b23 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: WebServer routes require authentication by default, and default Token login moves to a Provider plugin. +--- + +# Token Provider and route admission migration + +English | [中文](guide.zh.md) + +## Change + +Default Token verification and HTTP login exchanges move to `@deepseek-ai/dsh-host-authentication-token`. Connection removes BrowserAuth, `authorizeIndex`, `authenticatedUrl`, `requestRejection`, `ConnectionRequestRejection`, `peer(id)`, `createPeer.socketOwned`, `ConnectionAdmission`, and `admitConnection`. Token owns `/api/remote.mux` Socket claims through the post-admission `webserver/upgrade` waterfall. Cookie formats and `/connect` remain; valid v2 Cookies now also authenticate pages, without a page/API `purpose` field. + +WebServer registrations now accept `auth: 'anonymous' | 'required' | 'deny'` or a synchronous selector, defaulting to `required`. Previously public handlers, resources, fallbacks, and upgrades need explicit anonymous declarations. HTTP and upgrade handlers receive the admitted Peer as an optional trailing argument; resources keep their Peer argument. Connection source checks also apply to anonymous routes when its listener is active. + +## Migration + +1. Mount Token beside Connection and Credentials. Manually move `cookieMaxAgeDays` from `connection.config` to `authentication-token.config`. The old location has no effect and is neither migrated nor rejected; leaving Token's value unset uses 30 days. +2. Audit `webServer.register`, `registerFallback`, and `registerUpgrade` calls. Direct administrative handlers also require an owner Peer. Keep authenticated access for protected routes; declare `auth: 'anonymous'` for credential-free assets and login endpoints, and `auth: 'deny'` for blocked routes. Convert a bare fallback handler to `{ handler, auth }` when changing its policy. Check `trustedHosts` for every intended authority, including public assets. +3. Remove page adapters' `purpose` and repeated authentication calls. Consume the Peer passed to `(req, res, peer?)`, `(req, socket, head, peer?)`, or `resource(request, peer?)`. Render protected pages for that Peer. Trusted in-process `readResource(request, peer)` still uses its explicit Peer without source or Cookie checks, but respects `deny`. +4. Keep `printUrl`, `openBrowser`, and `publicUrl` on WebApp. After readiness, WebApp emits `webserver/entry-url(baseUrl, entries)`; listeners append `{ label, url, open }`. WebApp prints entries in order and opens the first eligible one outside SSH. No entries means no output or opening. Token contributes its signed URL without depending on WebApp. Custom HTTP carriers retain `webserver/request` before routing. +5. Providers inject `connection` and `connection.authentication`, retain their `createPeer({ principal, interactions })` results, and call `ctx.connection.authentication.register(provider)`. Keep `browserPeer` for trusted in-process use. Use `admit` instead of `requestRejection`. Without an authorization decision, `required` returns 503 and `anonymous` allows access. +6. Emit all `webserver/*` events with the WebServer as thisArg, including `index-inject` and `entry-url`. Ordinary listeners follow `webServer` isolation; `global: true` opts out. Run upgrade middleware after admission, before protocol handling; await `next()`. Token claims its API Peers only on `/api/remote.mux`. +7. Verify root Token login, existing Cookies, v2 page access, HTTP/WS, `/connect`, anonymous assets, and source-rejection 403. Duplicate mux Sockets still return 409; closing the owning Socket revokes credentials before Peer disposal. Only root Token queries exchange credentials. Token load failure grants no protected access. +8. Update custom Desktop shell/Host pairs together: per-process credentials travel over private IPC before ready; main processes use `authenticationCookie` and the ordinary Host URL. Keep credentials out of the renderer. Desktop may also mount Token. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md new file mode 100644 index 0000000000..62a1e26dfe --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/connection-page-peer/guide.zh.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: WebServer 路由默认要求认证,默认 Token 登录迁入 Provider 插件。 +--- + +# Token Provider 与路由准入迁移 + +[English](guide.md) | 中文 + +## 变更 + +默认 Token 验证与 HTTP 登录交换迁入 `@deepseek-ai/dsh-host-authentication-token`。Connection 移除 BrowserAuth、`authorizeIndex`、`authenticatedUrl`、`requestRejection`、`ConnectionRequestRejection`、`peer(id)`、`createPeer.socketOwned`、`ConnectionAdmission` 与 `admitConnection`。Token 通过准入后的 `webserver/upgrade` waterfall 拥有 `/api/remote.mux` Socket 认领。Cookie 格式与 `/connect` 保持;有效 v2 Cookie 也可认证页面,不再有页面/API `purpose` 字段。 + +WebServer 注册新增 `auth: 'anonymous' | 'required' | 'deny'` 或同步选择器,默认 `required`。此前公开的 handler、resource、回退与 upgrade 需要显式声明匿名。HTTP 与 upgrade handler 通过可选末尾参数接收准入 Peer;resource 保留已有 Peer 参数。Connection 监听器活动时,来源检查也适用于匿名路由。 + +## 迁移 + +1. 在 Connection 与 Credentials 旁挂载 Token。手动将 `cookieMaxAgeDays` 从 `connection.config` 移到 `authentication-token.config`。旧位置的值不生效,既不会自动迁移,也不会被拒绝;未配置 Token 的值时采用30天。 +2. 检查 `webServer.register`、`registerFallback` 与 `registerUpgrade` 调用。直接管理 handler 还必须要求 owner Peer。受保护路由保持认证要求;免凭据资源与登录端点声明 `auth: 'anonymous'`,禁止访问的路由声明 `auth: 'deny'`。改变裸回退 handler 策略时改为 `{ handler, auth }`。为所有预期 authority 检查 `trustedHosts`,包括公开资源。 +3. 移除页面适配器的 `purpose` 与重复认证调用。使用 `(req, res, peer?)`、`(req, socket, head, peer?)` 或 `resource(request, peer?)` 传入的 Peer,并为该 Peer 渲染受保护页面。可信进程内 `readResource(request, peer)` 仍使用显式 Peer,不检查来源或 Cookie,但遵守 `deny`。 +4. `printUrl`、`openBrowser` 与 `publicUrl` 保留在 WebApp。WebApp 就绪后触发 `webserver/entry-url(baseUrl, entries)`;监听器追加 `{ label, url, open }`。WebApp 按序打印入口,并在非 SSH 下打开首个允许自动打开的入口。没有入口就不输出、不打开。Token 贡献签名 URL,不依赖 WebApp。自定义 HTTP 载体在路由前保留 `webserver/request`。 +5. Provider 注入 `connection` 与 `connection.authentication`,保存 `createPeer({ principal, interactions })` 结果,并调用 `ctx.connection.authentication.register(provider)`。`browserPeer` 保留给可信进程内调用。使用 `admit` 替代 `requestRejection`。无人作出准入决策时,`required` 返回503,`anonymous` 允许访问。 +6. 发起所有 `webserver/*` 事件时传入 WebServer 作为 thisArg,包括 `index-inject` 与 `entry-url`。普通监听器遵循 `webServer` isolation;`global: true` 跳过过滤。在准入后、协议处理前运行 upgrade 中间件,并等待 `next()`。Token 仅在 `/api/remote.mux` 上认领自己的 API Peer。 +7. 验证根 Token 登录、已有 Cookie、v2 页面访问、HTTP/WS、`/connect`、匿名资源及来源拒绝403。重复 mux Socket 仍返回409;所属 Socket 关闭时先撤销凭据,再释放 Peer。只有根 Token query 执行凭据交换。Token 加载失败不授予受保护访问。 +8. 自定义 Desktop shell/Host 一同更新:每进程凭据在 ready 前通过私有 IPC 交付;主进程使用 `authenticationCookie` 与普通 Host URL。凭据不得进入 renderer。Desktop 也可挂载 Token。 diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index 4fe2652671..bcde443e70 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -48,7 +48,6 @@ import type { } from './types.ts' import { RemoteStreamMuxServer, - rejectRemoteStreamUpgrade, } from './stream-server.ts' import { REMOTE_EVENT_STREAM_ENDPOINT, @@ -264,46 +263,15 @@ export class TypertGatewayService extends Service implements TypertGateway { compression: resolved.websocketCompression === 'deflate', }, ) - const releases = new Set>() webCtx.effect(function* () { yield async () => { await mux.close() - await Promise.all(releases) } const route: WebUpgradeRoute = { path: REMOTE_STREAM_MUX_PATH, - handler: (req, socket, head) => { - const admission = webCtx.connection.admitConnection(req) - if ('rejection' in admission) { - rejectRemoteStreamUpgrade(socket, admission.rejection) - return - } - const release = (): void => { - // release removes the API Peer synchronously, before awaiting - // scope cleanup or any logical-stream iterator's return. - const done = admission.release().catch((error: unknown) => { - console.error('[api-gateway] Peer release failed:', error) - }) - releases.add(done) - void done.then(() => { releases.delete(done) }) - } - const closed = (): void => { - socket.removeListener('error', release) - release() - } - socket.on('error', release) - socket.once('close', closed) - if (socket.destroyed) { - closed() - return - } - try { - mux.handleUpgrade(req, socket, head, admission.peer) - } catch (error) { - release() - socket.destroy() - console.error('[api-gateway] Remote stream upgrade failed:', error) - } + auth: 'required', + handler: (req, socket, head, peer) => { + mux.handleUpgrade(req, socket, head, peer as PeerScope) }, } yield webCtx.webServer.registerUpgrade(route) diff --git a/packages/api/gateway/src/stream-server.ts b/packages/api/gateway/src/stream-server.ts index 6f7d205e3e..6f8e6b5124 100644 --- a/packages/api/gateway/src/stream-server.ts +++ b/packages/api/gateway/src/stream-server.ts @@ -477,21 +477,3 @@ function rawText(data: RawData): string { if (data instanceof ArrayBuffer) return Buffer.from(data).toString('utf8') return Buffer.from(data).toString('utf8') } - -/** - * Reject an upgrade without transferring socket ownership to ws. - * @param socket - carrier socket that receives the HTTP rejection. - * @param status - authentication or browser-trust rejection status. - */ -export function rejectRemoteStreamUpgrade(socket: Duplex, status: 401 | 403 | 409): void { - const reason = status === 401 ? 'Unauthorized' : status === 403 ? 'Forbidden' : 'Conflict' - const body = reason.toLowerCase() - socket.end([ - `HTTP/1.1 ${String(status)} ${reason}`, - 'Connection: close', - 'Content-Type: text/plain; charset=utf-8', - `Content-Length: ${String(Buffer.byteLength(body))}`, - '', - body, - ].join('\r\n')) -} diff --git a/packages/api/gateway/tests/authentication-provider.host.spec.ts b/packages/api/gateway/tests/authentication-provider.host.spec.ts new file mode 100644 index 0000000000..4857d06d70 --- /dev/null +++ b/packages/api/gateway/tests/authentication-provider.host.spec.ts @@ -0,0 +1,134 @@ +/** External authentication providers use existing Peer scopes over real HTTP and WebSocket. */ +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context } from '@deepseek-ai/cordis' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import Include from '@deepseek-ai/cordis-plugin-include' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import LocalCredentials from '@deepseek-ai/dsh-credentials-local' +import WebServer from '@deepseek-ai/dsh-host-webserver' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import TypertGateway from '@deepseek-ai/dsh-api-gateway' +import RemoteAccess from '@deepseek-ai/dsh-api-remote-access' +import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import WebSocket from 'ws' +import { parseRemoteStreamServerMessage, type RemoteStreamServerMessage } from '../src/stream-protocol.ts' +import OperatorConnectFixture from './operator-connect-fixture.ts' + +it('uses the provider-owned Peer for HTTP and streams, then closes only its scope on unload', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-provider-transport-')) + const ctx = new Context() + const clients: { socket: WebSocket; closed: Promise; errors: Error[] }[] = [] + onTestFinished(async () => { + await Promise.all(clients.map(async ({ socket, closed }) => { + if (socket.readyState !== WebSocket.CLOSED) socket.terminate() + await closed + })) + await ctx.fiber.dispose() + if (!isAbsolute(root) || dirname(root) !== resolve(tmpdir()) || !basename(root).startsWith('dsh-provider-transport-')) { + throw new Error(`refusing unexpected fixture cleanup path: ${root}`) + } + await rm(root, { recursive: true, force: true }) + }) + const peers = new Map() + const provider = (cookie: string) => ({ + inject: ['connection', 'connection.authentication'], + apply(scope: Context) { + const peer = scope.connection.createPeer({ principal: { kind: 'owner' }, interactions: 'none' }) + peers.set(cookie, peer) + scope.connection.authentication.register({ + authenticate(request) { + const header = request.headers instanceof Headers ? request.headers.get('cookie') : request.headers.cookie + return header === cookie ? peer : undefined + }, + }) + }, + }) + const rows = [ + { name: 'credentials', config: { path: join(root, '.credentials.yaml'), watch: false } }, + { name: 'webserver', config: { host: '127.0.0.1', port: 0 } }, + { name: 'connection' }, + { name: 'registry' }, + { name: 'access' }, + { name: 'gateway' }, + { name: 'fixture' }, + { id: 'provider-a', name: 'provider-a' }, + { id: 'provider-b', name: 'provider-b' }, + ] + const config = join(root, 'cordis.yml') + await writeFile(config, rows.map(row => `- ${JSON.stringify({ ...row, name: `cordis:${row.name}` })}`).join('\n') + '\n') + ctx.baseUrl = pathToFileURL(root).href + '/' + await ctx.plugin(Loader) + Object.assign(ctx.loader.builtins, { + include: Include, credentials: LocalCredentials, webserver: WebServer, + connection: Connection, registry: TypertRegistry, access: RemoteAccess, + gateway: TypertGateway, fixture: OperatorConnectFixture, + 'provider-a': provider('provider-a=valid'), 'provider-b': provider('provider-b=valid'), + }) + await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(config).href } }) + await ctx.loader.await() + const origin = `http://127.0.0.1:${ctx.webServer.port}` + const fixture = ctx.operatorConnectFixture + const peerA = peers.get('provider-a=valid') + const peerB = peers.get('provider-b=valid') + expect(peerA).toBeDefined() + expect(peerB).toBeDefined() + expect(peerA).not.toBe(peerB) + expect(peerA).not.toBe(ctx.connection.browserPeer) + + const identity = async (cookie: string, label: string): Promise => { + const response = await fetch(`${origin}/api/fixture/identity`, { + method: 'POST', headers: { cookie, 'content-type': 'application/json' }, + body: JSON.stringify({ type: 'client-request', rpcId: randomUUID(), method: 'fixture/identity', payload: { args: { label } } }), + }) + await response.text() + return response.status + } + const follow = async (cookie: string, label: string): Promise => { + const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, { headers: { cookie } }) + const closed = new Promise((done) => { socket.once('close', () => { done() }) }) + const errors: Error[] = [] + const frames: RemoteStreamServerMessage[] = [] + clients.push({ socket, closed, errors }) + socket.on('error', error => errors.push(error)) + socket.on('message', (data) => { + const text = Array.isArray(data) ? Buffer.concat(data).toString('utf8') + : Buffer.from(data instanceof ArrayBuffer ? new Uint8Array(data) : data).toString('utf8') + frames.push(parseRemoteStreamServerMessage(text)) + }) + await once(socket, 'open') + socket.send(JSON.stringify({ type: 'open', streamId: label, endpoint: 'fixture/follow', payload: { args: { label } } })) + await vi.waitFor(() => { + expect(frames).toContainEqual({ type: 'item', streamId: label, value: `${label}:ready` }) + }) + return socket + } + expect(await identity('provider-a=invalid', 'rejected')).toBe(401) + expect(fixture.calls.has('rejected')).toBe(false) + expect(await identity('provider-a=valid', 'http-a')).toBe(200) + expect(await identity('provider-b=valid', 'http-b')).toBe(200) + const socketA = await follow('provider-a=valid', 'stream-a') + const socketB = await follow('provider-b=valid', 'stream-b') + expect(fixture.calls.get('http-a')?.peer).toBe(peerA) + expect(fixture.calls.get('stream-a')?.peer).toBe(peerA) + expect(fixture.calls.get('http-b')?.peer).toBe(peerB) + expect(fixture.calls.get('stream-b')?.peer).toBe(peerB) + + const entry = [...ctx.loader.entries()].find(item => item.options.id === 'provider-a') + if (entry?.fiber === undefined) throw new Error('provider fixture did not activate') + await entry.fiber.dispose() + await vi.waitFor(() => { expect(socketA.readyState).toBe(WebSocket.CLOSED) }) + expect(peerA?.signal.aborted).toBe(true) + expect(peerB?.signal.aborted).toBe(false) + expect(socketB.readyState).toBe(WebSocket.OPEN) + await vi.waitFor(() => { expect(fixture.calls.get('stream-a')?.finished).toBe(true) }) + expect(await identity('provider-a=valid', 'after-a')).toBe(401) + expect(await identity('provider-b=valid', 'after-b')).toBe(200) + expect(fixture.calls.get('after-b')?.peer).toBe(peerB) + for (const client of clients) expect(client.errors).toEqual([]) +}) diff --git a/packages/api/gateway/tests/browser-credentials.ts b/packages/api/gateway/tests/browser-credentials.ts index 9bced52acc..111d9c5599 100644 --- a/packages/api/gateway/tests/browser-credentials.ts +++ b/packages/api/gateway/tests/browser-credentials.ts @@ -1,4 +1,7 @@ import type { Context } from '@deepseek-ai/cordis' +import type { IncomingMessage, ServerResponse } from 'node:http' +import * as Token from '@deepseek-ai/dsh-host-authentication-token' +import { BrowserAuth } from '@deepseek-ai/dsh-host-authentication-token/src/browser-auth.ts' const browserCookies = new WeakMap() @@ -23,22 +26,27 @@ export function provideBrowserCredentials(ctx: Context): void { * @param ctx - Host root with the Web server and Connection mounted. * @returns the `cookie` header value, cached per root. */ -export function browserCookie(ctx: Context): string { +export async function browserCookie(ctx: Context): Promise { const existing = browserCookies.get(ctx) if (existing !== undefined) return existing - const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` - const target = new URL(ctx.connection.authenticatedUrl(origin)) + await ctx.plugin(Token, { cookieMaxAgeDays: 30 }).await() + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + const target = new URL(auth.authenticatedUrl(`http://127.0.0.1:${String(ctx.webServer.port)}`)) let setCookie: string | undefined - ctx.connection.authorizeIndex({ + const request = { method: 'GET', url: `${target.pathname}${target.search}`, headers: { host: target.host }, - }, { - writeHead(_status, headers) { setCookie = headers?.['set-cookie'] }, + socket: { destroyed: false }, + } as IncomingMessage + const response = { + writeHead(_status: number, headers?: Readonly>) { setCookie = headers?.['set-cookie'] }, end() {}, - }) + } as ServerResponse + await ctx.waterfall('webserver/request', request, response, async () => {}) if (setCookie === undefined) throw new Error('gateway fixture did not receive a browser cookie') const cookie = setCookie.split(';', 1)[0]! browserCookies.set(ctx, cookie) + ctx.effect(() => () => { browserCookies.delete(ctx) }) return cookie } diff --git a/packages/api/gateway/tests/echo-stream.host.spec.ts b/packages/api/gateway/tests/echo-stream.host.spec.ts index 24a24f6918..2437f199c0 100644 --- a/packages/api/gateway/tests/echo-stream.host.spec.ts +++ b/packages/api/gateway/tests/echo-stream.host.spec.ts @@ -47,7 +47,7 @@ describe('the echo stream on each carrier', () => { it('echoes uplink frames through the WebSocket carrier', async () => { const ctx = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: unknown[] = [] diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index 708b093f0c..eca96aca95 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -445,7 +445,7 @@ describe('Typert Remote streams', () => { it('applies the configured compression mode to the Remote stream carrier', async () => { const { ctx } = await setup(true) const negotiating = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(negotiating, 'open') expect(negotiating.extensions).toContain('permessage-deflate') @@ -454,7 +454,7 @@ describe('Typert Remote streams', () => { const plain = await setup(true, { websocketCompression: 'none' }) const unnegotiated = new WebSocket(`ws://127.0.0.1:${String(plain.ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(plain.ctx) }, + headers: { cookie: await browserCookie(plain.ctx) }, }) await once(unnegotiated, 'open') expect(unnegotiated.extensions).toBe('') @@ -825,7 +825,7 @@ describe('Typert Remote streams', () => { it('reports configured frame capacity and the encoded envelope size for the current stream id', async () => { const { ctx, service } = await setup(true, { streamInboxBytes: 512 }) - const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { headers: { cookie: browserCookie(ctx) } }) + const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { headers: { cookie: await browserCookie(ctx) } }) await once(socket, 'open') try { const streamId = '界"window' @@ -846,7 +846,7 @@ describe('Typert Remote streams', () => { it('echoes uplink frames over the WebSocket carrier and fails misused uplinks per stream', async () => { const { ctx, service } = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -864,7 +864,9 @@ describe('Typert Remote streams', () => { ]) }) expect(service.returns).toBe(1) - expect(service.peers.at(-1)).toBe(ctx.connection.browserPeer) + const admitted = ctx.connection.admit({ headers: { host: `127.0.0.1:${String(ctx.webServer.port)}`, cookie: await browserCookie(ctx) } }) + if ('rejection' in admitted) throw new Error('expected the issued cookie to authenticate') + expect(service.peers.at(-1)).toBe(admitted.peer) sendOpen(socket, 'rejected', 'feed/echo', { prefix: '' }) socket.send(JSON.stringify({ type: 'item', streamId: 'rejected', value: 1 })) @@ -899,7 +901,7 @@ describe('Typert Remote streams', () => { it('fails a stream whose buffered uplink exceeds the configured inbox bytes', async () => { const { ctx } = await setup(true, { streamInboxBytes: 64 }) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -990,7 +992,7 @@ describe('Typert Remote streams', () => { it('uses the configured WebSocket heartbeat interval', { timeout: 1_000 }, async () => { const { ctx } = await setup(true, { websocketHeartbeatIntervalMs: 20 }) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) const ping = once(socket, 'ping') await once(socket, 'open') @@ -1003,7 +1005,7 @@ describe('Typert Remote streams', () => { it('multiplexes independent streams over one WebSocket and propagates cancellation', async () => { const { ctx, service } = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -1082,7 +1084,7 @@ describe('Typert Remote streams', () => { await events[Symbol.asyncIterator]().return?.() const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -1125,7 +1127,7 @@ describe('Typert Remote streams', () => { .toThrow('forwarded Remote event source is already registered') const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -1332,23 +1334,39 @@ describe('Typert Remote streams', () => { it('retries a colliding Remote event Client id before opening the second generation', async () => { const { ctx } = await setup(true) - // Connection minted the browser Peer id above; only the event Client ids are counted below. + await browserCookie(ctx) randomUuid.mockClear() const source = new RemoteEventSourceProbe() - const unregister = ctx.typertGateway.registerRemoteEvents(source.source, REMOTE_HOST) + const unregister = ctx.effect(() => ctx.typertGateway.registerRemoteEvents(source.source, REMOTE_HOST)) const firstId = '00000000-0000-4000-8000-000000000011' as ReturnType const secondId = '00000000-0000-4000-8000-000000000012' as ReturnType randomUuid.mockReturnValueOnce(firstId).mockReturnValueOnce(firstId).mockReturnValueOnce(secondId) - const first = await openEventClient(ctx, 'events-client-id-a') - const second = await openEventClient(ctx, 'events-client-id-b') + try { + const first = await openEventClient(ctx, 'events-client-id-a') + expect(first.clientId).toBe(firstId) + expect(randomUuid).toHaveBeenCalledTimes(1) + const second = await openEventClient(ctx, 'events-client-id-b') + expect(second.clientId).toBe(secondId) + expect(randomUuid).toHaveBeenCalledTimes(3) - expect(first.clientId).toBe(firstId) - expect(second.clientId).toBe(secondId) - expect(randomUuid).toHaveBeenCalledTimes(3) - first.socket.close() - second.socket.close() - await unregister() + const notification = { event: 'fixture/changed', args: ['both clients'] } + source.push(notification) + await vi.waitFor(() => { + for (const client of [first, second]) { + expect(client.frames).toContainEqual({ + type: 'item', streamId: client.streamId, value: { type: 'emit', ...notification }, + }) + } + }) + const closed = [once(first.socket, 'close'), once(second.socket, 'close')] + first.socket.close() + second.socket.close() + await Promise.all(closed) + } finally { + randomUuid.mockReset() + await unregister() + } }) it('fans one scoped waterfall out and accepts the first Client result', async () => { @@ -1578,7 +1596,7 @@ describe('Typert Remote streams', () => { it('validates the internal Remote event request and reports an absent source', async () => { const { ctx } = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -1685,7 +1703,7 @@ async function setup( async function acceptsSocket(ctx: Context): Promise { const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: browserCookie(ctx) }, + headers: { cookie: await browserCookie(ctx) }, }) const closed = new Promise((resolve) => { socket.once('close', () => { resolve() }) }) const opened = await once(socket, 'open').then(() => true, () => false) @@ -1767,7 +1785,7 @@ interface RemoteEventTestClient { async function openEventClient(ctx: Context, streamId: string): Promise { const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` - const cookie = browserCookie(ctx) + const cookie = await browserCookie(ctx) const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, { headers: { cookie }, }) diff --git a/packages/api/gateway/tests/gateway.host.spec.ts b/packages/api/gateway/tests/gateway.host.spec.ts index 2931b3d159..2e3e541faa 100644 --- a/packages/api/gateway/tests/gateway.host.spec.ts +++ b/packages/api/gateway/tests/gateway.host.spec.ts @@ -1,4 +1,6 @@ -import { createServer } from 'node:http' +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' +import * as Token from '@deepseek-ai/dsh-host-authentication-token' +import { BrowserAuth } from '@deepseek-ai/dsh-host-authentication-token/src/browser-auth.ts' import type { AddressInfo } from 'node:net' import { describe, expect, it } from 'vitest' import { Context, Service, symbols } from '@deepseek-ai/cordis' @@ -6,7 +8,6 @@ import { z } from 'zod' import { apply as applyConnection, inject as connectionInject } from '@deepseek-ai/dsh-client-connection' import type { ConnectionRpcHandler, - HostConnectionHandle, PeerScope, } from '@deepseek-ai/dsh-client-connection' import type { WebServer, WebRoute } from '@deepseek-ai/dsh-host-webserver' @@ -145,10 +146,6 @@ class FakeConnectionService extends Service { }), } } - - requestRejection(): undefined { - return undefined - } } function fakeHttpServer(routes: WebRoute[]): Pick { @@ -165,9 +162,18 @@ function fakeHttpServer(routes: WebRoute[]): Pick }> { +async function serveRoute(ctx: Context, route: WebRoute): Promise<{ readonly origin: string; close(): Promise }> { const server = createServer((request, response) => { - void route.handler(request, response) + const admission = ctx.bail('webserver/authorize', { + headers: request.headers, method: request.method, socket: request.socket, + url: new URL(request.url ?? '/', 'http://localhost'), transport: 'http', + }, 'required') + if (admission?.kind !== 'allow') { + response.writeHead(admission?.status ?? 503) + response.end() + return + } + void route.handler(request, response, admission.peer) }) await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) const address = server.address() as AddressInfo @@ -182,18 +188,21 @@ async function serveRoute(route: WebRoute): Promise<{ readonly origin: string; c } } -/** Exchange a Connection launch token without mounting the frontend fallback. */ -function browserCookie(connection: HostConnectionHandle, origin: string): string { - const target = new URL(connection.authenticatedUrl(origin)) +/** Exchange the token plugin's launch URL for the separate HTTP fixture's origin. */ +async function browserCookie(ctx: Context, origin: string): Promise { + await ctx.plugin(Token, { cookieMaxAgeDays: 30 }).await() + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + const target = new URL(auth.authenticatedUrl(origin)) let setCookie: string | undefined - connection.authorizeIndex({ - method: 'GET', - url: `${target.pathname}${target.search}`, - headers: { host: target.host }, - }, { - writeHead(_status, headers) { setCookie = headers?.['set-cookie'] }, + const request = { + method: 'GET', url: `${target.pathname}${target.search}`, + headers: { host: target.host }, socket: { destroyed: false }, + } as IncomingMessage + const response = { + writeHead(_status: number, headers?: Readonly>) { setCookie = headers?.['set-cookie'] }, end() {}, - }) + } as ServerResponse + await ctx.waterfall('webserver/request', request, response, async () => {}) if (setCookie === undefined) throw new Error('gateway fixture did not receive an authentication cookie') return setCookie.split(';', 1)[0]! } @@ -1389,8 +1398,8 @@ describe('TypertGatewayService', () => { let strictActive = true const apiRoute = routes.find(route => route.path === '/api') if (apiRoute === undefined) throw new Error('fixture API route was not installed') - const server = await serveRoute(apiRoute) - const cookie = browserCookie(ctx.connection, server.origin) + const server = await serveRoute(ctx, apiRoute) + const cookie = await browserCookie(ctx, server.origin) try { const response = await fetch(`${server.origin}/api/goals/create`, { diff --git a/packages/api/gateway/tests/operator-connect.host.spec.ts b/packages/api/gateway/tests/operator-connect.host.spec.ts index 1868f33bf6..e06b30e916 100644 --- a/packages/api/gateway/tests/operator-connect.host.spec.ts +++ b/packages/api/gateway/tests/operator-connect.host.spec.ts @@ -2,7 +2,8 @@ import { randomUUID } from 'node:crypto' import { once } from 'node:events' import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { IncomingMessage } from 'node:http' +import type { IncomingMessage } from 'node:http' +import type { Duplex } from 'node:stream' import { tmpdir } from 'node:os' import { basename, dirname, isAbsolute, join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' @@ -10,6 +11,8 @@ import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import * as Connection from '@deepseek-ai/dsh-client-connection' +import * as Token from '@deepseek-ai/dsh-host-authentication-token' +import { BrowserAuth } from '@deepseek-ai/dsh-host-authentication-token/src/browser-auth.ts' import LocalCredentials from '@deepseek-ai/dsh-credentials-local' import WebServer from '@deepseek-ai/dsh-host-webserver' import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static' @@ -17,7 +20,7 @@ import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import TypertGateway from '@deepseek-ai/dsh-api-gateway' import RemoteAccess from '@deepseek-ai/dsh-api-remote-access' import { afterEach, describe, expect, it, vi } from 'vitest' -import WebSocket from 'ws' +import WebSocket, { WebSocketServer } from 'ws' import { z } from 'zod' import { parseRemoteStreamServerMessage, type RemoteStreamServerMessage } from '../src/stream-protocol.ts' import { RemoteStreamMuxServer } from '../src/stream-server.ts' @@ -84,6 +87,95 @@ describe('operator connect through Loader composition', () => { await vi.waitFor(() => { expect(call(host, 'follow').finished).toBe(true) }) }) + it('does not claim or revoke an API Peer for non-mux WebSocket upgrades', async () => { + const host = await boot() + const inspector = new WebSocketServer({ noServer: true }) + host.ctx.effect(() => () => new Promise((resolve, reject) => { + inspector.close((error) => { + if (error) reject(error) + else resolve() + }) + }), 'fixture: non-mux WebSocket server') + const peers: Array = [] + host.ctx.effect(() => host.ctx.webServer.registerUpgrade({ + path: '/inspector/devtools/cdp', auth: 'required', + handler(request, socket, head, peer) { + peers.push(peer) + inspector.handleUpgrade(request, socket, head, () => {}) + }, + }), 'fixture: non-mux upgrade route') + const cookie = await exchange(host, 'none') + await success(host, cookie, 'fixture/identity', { label: 'non-mux-peer' }) + const peer = call(host, 'non-mux-peer').peer + + const first = socketClient(host, cookie, '/inspector/devtools/cdp') + await once(first.socket, 'open') + const api = socketClient(host, cookie, '/api/remote.mux?fixture=scope') + await once(api.socket, 'open') + await close(first) + expect(peer.signal.aborted).toBe(false) + await success(host, cookie, 'fixture/identity', { label: 'after-cdp-close' }) + + const second = socketClient(host, cookie, '/inspector/devtools/cdp') + await once(second.socket, 'open') + await close(second) + expect(peers).toEqual([peer, peer]) + expect(peer.signal.aborted).toBe(false) + expect(await refusedMux(host, cookie)).toBe(409) + await close(api) + expect((await rpc(host, cookie, 'fixture/identity', { label: 'after-mux-close' })).status).toBe(401) + }) + + it('uses the Peer WebServer authenticated without a second provider pass', async () => { + const host = await boot() + const peer = host.ctx.connection.createPeer({ principal: { kind: 'owner' } }) + const authenticate = vi.fn(() => peer) + const unregister = host.ctx.connection.authentication.register({ authenticate }) + try { + const client = await mux(host, 'fixture=credential') + expect(authenticate).toHaveBeenCalledOnce() + await close(client) + expect(peer.signal.aborted).toBe(false) + await peer.dispose() + expect(peer.signal.aborted).toBe(true) + } finally { await unregister() } + }) + + it('rejects a WebSocket upgrade with 503 when authentication providers fail', async () => { + const host = await boot() + const failure = new Error('fixture authentication unavailable') + const authenticate = vi.fn(() => { throw failure }) + const unregister = host.ctx.connection.authentication.register({ authenticate }) + try { + const client = socketClient(host, 'unrecognized=credential') + const response = await new Promise((resolve, reject) => { + client.socket.once('unexpected-response', (_request, response) => { resolve(response) }) + client.socket.once('open', () => { reject(new Error('unavailable authentication admitted the upgrade')) }) + client.socket.once('error', reject) + }) + const chunks: Buffer[] = [] + response.on('data', (chunk: Buffer) => { chunks.push(chunk) }) + await once(response, 'end') + client.socket.terminate() + await client.closed + + expect(response.statusCode).toBe(503) + expect(response.statusMessage).toBe('Service Unavailable') + expect(response.headers).toMatchObject({ + connection: 'close', + 'content-type': 'text/plain; charset=utf-8', + 'content-length': String(Buffer.byteLength('service unavailable')), + }) + expect(Buffer.concat(chunks).toString('utf8')).toBe('service unavailable') + expect(authenticate).toHaveBeenCalledOnce() + expect(host.fixture.calls.size).toBe(0) + } finally { + await unregister() + } + expect(await refusedMux(host, 'unrecognized=credential')).toBe(401) + await close(await mux(host, await exchange(host, 'none'))) + }) + it('reports failed Operator release without retaining its credential or blocking shutdown', async () => { const host = await boot() const cookie = await exchange(host, 'none') @@ -99,7 +191,7 @@ describe('operator connect through Loader composition', () => { try { await close(await mux(host, cookie)) await vi.waitFor(() => { - expect(report).toHaveBeenCalledWith('[api-gateway] Peer release failed:', failure) + expect(report).toHaveBeenCalledWith('[host-authentication-token] Peer release failed:', failure) }) expect((await rpc(host, cookie, 'fixture/identity', { label: 'refused' })).status).toBe(401) expect(host.fixture.calls.has('refused')).toBe(false) @@ -112,16 +204,15 @@ describe('operator connect through Loader composition', () => { } }) - it('releases admission when the underlying socket is destroyed before upgrade', async () => { + it.each([false, true])('releases admission when the socket is destroyed before upgrade (closed: %s)', async (alreadyClosed) => { const host = await boot() const cookie = await exchange(host, 'none') - const admit = host.ctx.connection.admitConnection.bind(host.ctx.connection) - const admission = vi.spyOn(host.ctx.connection, 'admitConnection').mockImplementationOnce((request) => { - const result = admit(request) - if (!(request instanceof IncomingMessage)) throw new Error('fixture expected a Node upgrade request') - request.socket.destroy() - return result - }) + const remove = host.ctx.on('webserver/upgrade', async (_request, socket, _head, _peer, next) => { + const closed = new Promise((resolve) => { socket.once('close', () => { resolve() }) }) + socket.destroy() + if (alreadyClosed) await closed + await next() + }, { prepend: true }) const upgrade = vi.spyOn(RemoteStreamMuxServer.prototype, 'handleUpgrade') try { const client = socketClient(host, cookie) @@ -131,11 +222,51 @@ describe('operator connect through Loader composition', () => { expect((await rpc(host, cookie, 'fixture/identity', { label: 'refused' })).status).toBe(401) expect(host.fixture.calls.has('refused')).toBe(false) } finally { - admission.mockRestore() + remove() upgrade.mockRestore() } }) + it('delegates an anonymous upgrade without claiming its socket', async () => { + const host = await boot() + const handler = vi.fn((_request: IncomingMessage, socket: Duplex, _head: Buffer, peer?: Connection.PeerScope) => { + expect(peer).toBeUndefined() + socket.destroy() + }) + const remove = host.ctx.webServer.registerUpgrade({ path: '/anonymous-upgrade', auth: 'anonymous', handler }) + try { + const client = socketClient(host, '', '/anonymous-upgrade') + await client.closed + expect(handler).toHaveBeenCalledOnce() + } finally { remove() } + }) + + it('refuses a Token Peer aborted between authentication and socket claim', async () => { + const host = await boot() + const cookie = await exchange(host, 'none') + await success(host, cookie, 'fixture/identity', { label: 'abort-before-claim' }) + const peer = call(host, 'abort-before-claim').peer + const lifetime = new AbortController() + const remove = host.ctx.on('webserver/upgrade', async (_request, _socket, _head, admittedPeer, next) => { + expect(admittedPeer).toBe(peer) + Object.defineProperty(peer, 'signal', { value: lifetime.signal }) + lifetime.abort() + await next() + }, { prepend: true }) + const upgrade = vi.spyOn(RemoteStreamMuxServer.prototype, 'handleUpgrade') + try { + const client = socketClient(host, cookie) + await client.closed + expect(upgrade).not.toHaveBeenCalled() + expect((await rpc(host, cookie, 'fixture/identity', { label: 'refused' })).status).toBe(401) + expect(host.fixture.calls.has('refused')).toBe(false) + } finally { + remove() + upgrade.mockRestore() + await peer.dispose() + } + }) + it('releases admission and closes the socket when the WebSocket upgrade throws', async () => { const host = await boot() const cookie = await exchange(host, 'none') @@ -143,21 +274,118 @@ describe('operator connect through Loader composition', () => { const upgrade = vi.spyOn(RemoteStreamMuxServer.prototype, 'handleUpgrade').mockImplementationOnce(() => { throw failure }) - const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const report = vi.fn() + const remove = host.ctx.logger.exporter({ export: report }) try { const client = socketClient(host, cookie) await client.closed expect(client.socket.readyState).toBe(WebSocket.CLOSED) - expect(report).toHaveBeenCalledWith('[api-gateway] Remote stream upgrade failed:', failure) + await vi.waitFor(() => { expect(report).toHaveBeenCalledWith(expect.objectContaining({ type: 'warn', args: [failure] })) }) expect((await rpc(host, cookie, 'fixture/identity', { label: 'refused' })).status).toBe(401) expect(host.fixture.calls.has('refused')).toBe(false) await close(await mux(host, await exchange(host, 'none'))) } finally { upgrade.mockRestore() - report.mockRestore() + await remove() } }) + it('revokes on socket error synchronously and refuses an already-authenticated late upgrade', async () => { + const host = await boot() + const cookie = await exchange(host, 'none') + await success(host, cookie, 'fixture/identity', { label: 'error-owner' }) + const peer = call(host, 'error-owner').peer + const captured = Promise.withResolvers() + host.ctx.on('webserver/upgrade', async (_request, socket, _head, _peer, next) => { + captured.resolve(socket) + await next() + }) + const first = await mux(host, cookie) + const socket = await captured.promise + const entered = Promise.withResolvers() + const resume = Promise.withResolvers() + const cleaned = Promise.withResolvers() + const dispose = peer.dispose.bind(peer) + const disposing = vi.spyOn(peer, 'dispose').mockImplementation(async () => { + await cleaned.promise + await dispose() + }) + host.ctx.on('webserver/upgrade', async (_request, _socket, _head, _peer, next) => { + entered.resolve(undefined) + await resume.promise + await next() + }, { prepend: true }) + const late = socketClient(host, cookie) + await entered.promise + try { + socket.emit('error', new Error('fixture socket error')) + expect(host.ctx.connection.admit({ headers: { host: new URL(host.origin).host, cookie } })) + .toEqual({ rejection: 401 }) + expect(peer.signal.aborted).toBe(false) + resume.resolve(undefined) + await late.closed + expect(late.socket.readyState).toBe(WebSocket.CLOSED) + await first.closed + expect(disposing).toHaveBeenCalledOnce() + } finally { + resume.resolve(undefined) + cleaned.resolve(undefined) + await dispose() + disposing.mockRestore() + } + }) + + it('awaits Token-owned socket cleanup on unload without claiming another provider socket', async () => { + const host = await boot() + const cookie = await exchange(host, 'none') + await success(host, cookie, 'fixture/identity', { label: 'unload-owner' }) + const peer = call(host, 'unload-owner').peer + const owned = await mux(host, cookie) + const external = host.ctx.connection.createPeer({ principal: { kind: 'owner' } }) + Object.defineProperty(external, 'id', { value: peer.id }) + const unregister = host.ctx.connection.authentication.register({ authenticate: () => external }) + const other = await mux(host, 'fixture=external') + await unregister() + const finish = Promise.withResolvers() + const dispose = peer.dispose.bind(peer) + const disposing = vi.spyOn(peer, 'dispose').mockImplementation(async () => { + await finish.promise + await dispose() + }) + const token = [...host.ctx.loader.entries()].find(entry => entry.options.name === 'cordis:@deepseek-ai/dsh-host-authentication-token') + if (token?.fiber === undefined) throw new Error('Token provider did not activate') + const entered = Promise.withResolvers() + const resume = Promise.withResolvers() + host.ctx.on('webserver/upgrade', async (_request, _socket, _head, _peer, next) => { + entered.resolve(undefined) + await resume.promise + await next() + }, { prepend: true }) + const late = socketClient(host, cookie) + await entered.promise + let settled = false + const unloading = token.fiber.dispose().then(() => { settled = true }) + try { + await owned.closed + expect(settled).toBe(false) + resume.resolve(undefined) + await late.closed + expect(late.socket.readyState).toBe(WebSocket.CLOSED) + expect(other.socket.readyState).toBe(WebSocket.OPEN) + expect(external.signal.aborted).toBe(false) + expect(host.ctx.connection.admit({ headers: { host: new URL(host.origin).host, cookie } })) + .toEqual({ rejection: 401 }) + } finally { + resume.resolve(undefined) + finish.resolve(undefined) + await unloading + disposing.mockRestore() + } + expect(peer.signal.aborted).toBe(true) + await close(other) + await external.dispose() + }) + it('lets an admitted unary finish after its lifecycle socket closes', async () => { const host = await boot() const cookie = await exchange(host, 'none') @@ -180,7 +408,9 @@ describe('operator connect through Loader composition', () => { const pageCookie = await exchange(host, 'html') const page = await mux(host, pageCookie) await success(host, pageCookie, 'fixture/identity', { label: 'browser' }) - expect(call(host, 'browser').peer === host.ctx.connection.browserPeer).toBe(true) + expect(call(host, 'browser').peer === host.ctx.connection.browserPeer).toBe(false) + expect(host.ctx.connection.authentication.authenticate({ headers: { host: new URL(host.origin).host, cookie: pageCookie } })) + .toEqual({ peer: call(host, 'browser').peer }) const ready = await events(page) const otherCookie = await exchange(host, 'answer') const other = await mux(host, otherCookie) @@ -212,6 +442,7 @@ async function boot(): Promise { { name: '@deepseek-ai/dsh-credentials-local', config: { path: join(root, '.credentials.yaml'), watch: false } }, { name: '@deepseek-ai/dsh-host-webserver', config: { host: '127.0.0.1', port: 0 } }, { name: '@deepseek-ai/dsh-client-connection' }, + { name: '@deepseek-ai/dsh-host-authentication-token' }, { name: '@deepseek-ai/dsh-host-frontend-static', config: { distIndex } }, { name: '@deepseek-ai/dsh-typert-registry' }, { name: '@deepseek-ai/dsh-api-remote-access' }, @@ -228,6 +459,7 @@ async function boot(): Promise { '@deepseek-ai/dsh-credentials-local': LocalCredentials, '@deepseek-ai/dsh-host-webserver': WebServer, '@deepseek-ai/dsh-client-connection': Connection, + '@deepseek-ai/dsh-host-authentication-token': Token, '@deepseek-ai/dsh-host-frontend-static': FrontendStatic, '@deepseek-ai/dsh-typert-registry': TypertRegistry, '@deepseek-ai/dsh-api-remote-access': RemoteAccess, @@ -247,7 +479,8 @@ async function boot(): Promise { } async function exchange(host: Host, mode: 'html' | 'none' | 'answer'): Promise { - const target = new URL(host.ctx.connection.authenticatedUrl(`${host.origin}${mode === 'html' ? '/' : '/connect'}`)) + const auth = await BrowserAuth.create(host.ctx.root, host.ctx.credentials, 30) + const target = new URL(auth.authenticatedUrl(`${host.origin}${mode === 'html' ? '/' : '/connect'}`)) if (mode !== 'html') target.searchParams.set('interactions', mode) const response = await fetch(target, { redirect: 'manual', headers: { accept: mode === 'html' ? 'text/html' : 'application/json' } }) expect(response.status).toBe(mode === 'html' ? 303 : 302) @@ -257,8 +490,8 @@ async function exchange(host: Host, mode: 'html' | 'none' | 'answer'): Promise((resolve) => { socket.once('close', () => { resolve() }) }) const frames: RemoteStreamServerMessage[] = [] const errors: Error[] = [] diff --git a/packages/api/remotes/tests/built-lib.e2e.ts b/packages/api/remotes/tests/built-lib.e2e.ts index 9a7f3f23c8..e2105406c2 100644 --- a/packages/api/remotes/tests/built-lib.e2e.ts +++ b/packages/api/remotes/tests/built-lib.e2e.ts @@ -15,18 +15,19 @@ const artifact = (path: string): string => join(root, path) const artifactUrl = (path: string): string => pathToFileURL(artifact(path)).href const requiredArtifacts = [ - 'packages/client/connection/lib/client.js', + 'packages/client/connection/lib/client.browser.js', 'packages/client/connection/lib/index.js', + 'packages/host/authentication-token/lib/index.js', 'packages/api/remotes/lib/client.js', 'packages/core/agent/lib/index.js', 'packages/core/session/lib/index.js', 'packages/util/brand/lib/index.js', 'packages/goal/goal/lib/index.js', 'packages/goal/goal/lib/typert.host.js', - 'packages/api/gateway/lib/client.js', + 'packages/api/gateway/lib/client.browser.js', 'packages/api/gateway/lib/index.js', 'packages/api/remote-access/lib/index.js', - 'packages/typert/registry/lib/client.js', + 'packages/typert/registry/lib/client.browser.js', 'packages/typert/registry/lib/index.js', 'packages/session/session-projection/lib/index.js', ].every(path => existsSync(artifact(path))) @@ -36,14 +37,15 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { const urls = Object.fromEntries(Object.entries({ agent: 'packages/core/agent/lib/index.js', brand: 'packages/util/brand/lib/index.js', - apiGatewayClient: 'packages/api/gateway/lib/client.js', + apiGatewayClient: 'packages/api/gateway/lib/client.browser.js', apiGatewayHost: 'packages/api/gateway/lib/index.js', - connectionClient: 'packages/client/connection/lib/client.js', + connectionClient: 'packages/client/connection/lib/client.browser.js', connectionHost: 'packages/client/connection/lib/index.js', + tokenProvider: 'packages/host/authentication-token/lib/index.js', goal: 'packages/goal/goal/lib/index.js', goalTypert: 'packages/goal/goal/lib/typert.host.js', remoteAccess: 'packages/api/remote-access/lib/index.js', - registryClient: 'packages/typert/registry/lib/client.js', + registryClient: 'packages/typert/registry/lib/client.browser.js', registryHost: 'packages/typert/registry/lib/index.js', remotesClient: 'packages/api/remotes/lib/client.js', session: 'packages/core/session/lib/index.js', @@ -87,7 +89,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { return next ?? current }, }) - await host.plugin({ inject: connectionHost.inject, apply: connectionHost.apply }) + await host.plugin({ inject: connectionHost.inject, apply: connectionHost.apply }).await() await host.plugin(TypertRegistry) await host.plugin(SessionProjectionRegistry) await host.plugin(AgentRegistry) @@ -126,14 +128,15 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { } const apiRoute = apiRoutes[0] const server = createServer((request, response) => { - if ((request.url ?? '/').startsWith('/?')) { - if (host.connection.authorizeIndex(request, response)) { - response.writeHead(200, { 'content-type': 'text/html' }) - response.end('shell') + void host.waterfall(host.webServer, 'webserver/request', request, response, async () => { + const admission = host.connection.admit(request) + if ('rejection' in admission) { + response.writeHead(admission.rejection) + response.end() + return } - return - } - void apiRoute.handler(request, response) + await apiRoute.handler(request, response, admission.peer) + }) }) await new Promise(resolveListen => server.listen(0, '127.0.0.1', resolveListen)) const address = server.address() @@ -145,7 +148,15 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { const previousFetch = globalThis.fetch try { globalThis.document = { baseURI: origin + '/' } - const login = await fetch(host.connection.authenticatedUrl(origin), { redirect: 'manual' }) + await host.plugin(await import(urls.tokenProvider), { cookieMaxAgeDays: 30 }).await() + const entries = [] + host.emit(host.webServer, 'webserver/entry-url', origin + '/', entries) + if (entries.length !== 1) throw new Error('Token did not contribute exactly one login URL') + const launchUrl = entries[0].url + const unauthorized = await fetch(origin + '/api') + const unauthorizedStatus = unauthorized.status + await unauthorized.text() + const login = await fetch(launchUrl, { redirect: 'manual' }) const setCookie = login.headers.get('set-cookie') if (login.status !== 303 || setCookie === null) throw new Error('browser token exchange failed') const cookie = setCookie.split(';', 1)[0] @@ -202,6 +213,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { const agentContext = client.extend({ builtAgentId: scopedAgent.id }) const scopedResult = await agentContext.remote.goals.create({ objective: 'scoped goal', maxGoalRounds: 3 }) const result = { + unauthorizedStatus, invalidResult, rootResult: rootResult.value, rootEdit: rootEdit.value, @@ -227,8 +239,11 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { ` const result = await runPlainNode(script) + expect(result.killed, `stderr:\n${result.stderr}`).toBe(false) + expect(result.signal, `stderr:\n${result.stderr}`).toBeNull() expect(result.exitCode, `stderr:\n${result.stderr}`).toBe(0) const output = JSON.parse(result.stdout.trim().split('\n').at(-1) ?? '{}') as { + unauthorizedStatus: number invalidResult: { ok: boolean; error?: { code: string } } rootResult: { ref: { id: string; revision: number } } rootEdit: { objective: string; revision: number } @@ -239,6 +254,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { scopedEvents: number } expect(output).toMatchObject({ + unauthorizedStatus: 401, invalidResult: { ok: false, error: { code: 'gateway/input-invalid' } }, rootResult: { ref: { revision: 1 } }, rootEdit: { objective: 'edited root goal', revision: 2 }, @@ -256,6 +272,8 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { /** Execute one ESM script without tsx or a TypeScript loader. */ function runPlainNode(script: string): Promise<{ readonly exitCode: number | null + readonly killed: boolean + readonly signal: string | null readonly stdout: string readonly stderr: string }> { @@ -267,6 +285,8 @@ function runPlainNode(script: string): Promise<{ }, (error, stdout, stderr) => { resolveRun({ exitCode: error === null ? 0 : typeof error.code === 'number' ? error.code : null, + killed: error?.killed === true, + signal: error?.signal ?? null, stdout, stderr, }) diff --git a/packages/api/workspace-files/tests/binary-rpc.spec.ts b/packages/api/workspace-files/tests/binary-rpc.spec.ts index 40ce2472be..ae05822d2e 100644 --- a/packages/api/workspace-files/tests/binary-rpc.spec.ts +++ b/packages/api/workspace-files/tests/binary-rpc.spec.ts @@ -6,8 +6,7 @@ import SessionStore from '@deepseek-ai/dsh-session' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import TypertGateway from '@deepseek-ai/dsh-api-gateway' import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection/src/rpc-host.ts' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import { createWebConnectionRpc } from '@deepseek-ai/dsh-client-connection/src/client/rpc.ts' import WorkspaceFiles, { type WorkspaceByteReadOptions } from '../src/index.ts' import { openWorkspace, type Harness } from './harness.ts' @@ -22,7 +21,7 @@ beforeEach(async () => { await ctx.plugin(TypertRegistry) await ctx.plugin(RemoteAccessService) await ctx.plugin(TypertGateway) - await ctx.plugin((scope) => { new HostConnectionService(scope, [], {} as BrowserAuth) }) + await ctx.plugin((scope) => { new ConnectionAuthentication(scope); new HostConnectionService(scope, []) }) await ctx.plugin(WorkspaceFiles, { maxBytes: 8, maxFileBytes: 4, diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index 1a650beec8..de0886efaa 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -21,11 +21,11 @@ en: e3cac911f080d8ef zh: 60749e9f5c39c1bc /deepseek-ai-dsh-web-app/use-this-package/configuration: - en: f876c60a37e3cb0e - zh: 42a535554fe4bc40 + en: 8a860bd7fe5743e4 + zh: 7d5bbcf734160e86 /deepseek-ai-dsh-web-app/use-this-package/listening-trust-and-public-deployments: - en: e6ddea1d2fc40501 - zh: ff08b6fa3fc24136 + en: d740bac72710544c + zh: 40508e8b99bb46bd /deepseek-ai-dsh-web-app/use-this-package/running-over-ssh: en: df205a26b6d49168 zh: e46ed7cf9e06248a @@ -33,8 +33,8 @@ en: 1f16cd1737256729 zh: 1d24cd133933ad9e /deepseek-ai-dsh-web-app/understand-the-implementation: - en: cc4f6d02a4d11d58 - zh: 276e0929502b4fca + en: 567cf3afa68e6b68 + zh: f065cdb56c28d4e6 /deepseek-ai-dsh-web-app/understand-the-implementation/patch-semantics: en: a6d126f30b1594d7 zh: 7f0ccc8a55d6f743 @@ -42,11 +42,11 @@ en: 0b22e03e28d41420 zh: fd45a97dd4336c25 /deepseek-ai-dsh-web-app/understand-the-implementation/readiness: - en: 973128fd346869df - zh: 54e6792f9f82a192 + en: 7877e9da8aaa5151 + zh: 3e96acf88f81baf2 /deepseek-ai-dsh-web-app/understand-the-implementation/source-map: - en: 58800b6f2142c34f - zh: 10bf512b16db1cb8 + en: 6d8d71d9a7168bdd + zh: c9b3f4dadc3d8367 /deepseek-ai-dsh-web-app/further-exploration: en: f81694f7424e2988 zh: 6643f9227039e228 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index aed6c22d91..9fdb2d8b51 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -54,11 +54,13 @@ The `minimal` agent preset uses a persistent shell, the `read_image` tool, and a | Field | Default | Meaning | |---|---|---| -| `openBrowser` | `true` | Open the default browser after startup; SSH launches suppress it | -| `printUrl` | `true` | Print the `dsh web:` URL line at startup | +| `printUrl` | `true` | Print contributed entry URLs after startup settles | +| `openBrowser` | `true` | Open the first eligible entry after startup, except under SSH | | `surfaceContext` | `true` | Expose `DSH_WEB_URL` to the agent's shell commands | | `publicUrl` | Unset | Advertised HTTP(S) application root; otherwise announce the bind-address URL | +WebApp owns `printUrl` and `openBrowser`. This bundle enables URL printing and maps the parsed `--no-open` setting to the runtime. After readiness, synchronous `webserver/entry-url` listeners contribute complete entries. WebApp prints every entry as `label: url` when printing is enabled and opens only the first entry marked `open: true` when browser opening is enabled outside SSH. No entries means no output or opening. + The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-web-app) lists this runtime plugin's accepted fields and their JSDoc. The shipped composition inserts the `schedule` service row and the `ui-schedule` task page row, while the clock reading and the four reminder tools belong to the `standard`, `cordis`, and `ptc` presets. The `tool-subagent` and `tool-subagent-fork` rows in those presets deny the four tools, so a delegated child's scope never lists them. The `standard`, `cordis`, and `ptc` presets set `config.interrupt: false` on their `tool-subagent-control` rows. To expose `interrupt_agent`, including in Team mode, override the relevant preset declaration as described in the [migration steps](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md); changing the disabled Host row does not change preset tools. @@ -84,7 +86,7 @@ Without `--public-url`, mapped IPv6 loopback binds such as `::ffff:127.0.0.1` ad Neither the advertised URL nor the browser-trust fence protects the port itself, so restrict the port to the trusted proxy or network. -The printed URL contains a process credential; share it only with intended users. `printUrl: false` suppresses the line with or without `--public-url`, and the credential never appears in the model context or in `DSH_WEB_URL`. +The printed URL contains a process credential; share it only with intended users. `printUrl: false` on the WebApp runtime suppresses the line with or without `--public-url`, and the credential never appears in the model context or in `DSH_WEB_URL`. ### Running over SSH @@ -106,7 +108,7 @@ The packaged skill uses the custom skill root: a same-named project skill overri
Implementation internals — click to expand -The bundle is one patch layer of five files plus one runtime glue plugin: `cordis.patch.yml` carries the host rows and the preset registry, and each `presets/.patch.yml` inserts one shipped preset declaration, applied in the order `dsh.bundle.patch` lists them. The storage stack and projection cache come from `dsh-base`; the web overlay's workspace and message-feedback rows consume that shared `storageDomain` service. The patch restates the surface-specific values the base deliberately omits, inserts the web-only host rows and browser roster, then moves the agent plane behind presets. The glue plugin owns dist serving, the advertised application URL, the plain-HTTP exposure warning, the bash variable, and the readiness announcements. The `office-kit` row mounts one lazy [Office conversion provider](../../document/office-kit/README.md) for Host consumers, including Desktop compositions using this bundle, and keeps converted files under `$DSH_HOME/office-kit/outputs`. The `standard` and `ptc` presets mount the [Office tools](../../document/tool-office/README.md) in every profile, whether or not Kit is installed, and declare them after an Office skill loads; the `minimal` preset omits them. The conversion service's Remote methods authorize preview reads, while Document Preview owns the Office viewer and Client cache. +The bundle is one patch layer of five files plus one runtime glue plugin: `cordis.patch.yml` carries the host rows and the preset registry, and each `presets/.patch.yml` inserts one shipped preset declaration, applied in the order `dsh.bundle.patch` lists them. The storage stack and projection cache come from `dsh-base`; the web overlay's workspace and message-feedback rows consume that shared `storageDomain` service. The patch restates the surface-specific values the base deliberately omits, inserts the web-only host rows and browser roster, then moves the agent plane behind presets. The glue plugin owns dist serving, the advertised application URL, the plain-HTTP exposure warning, and the bash variable. WebApp owns startup URL publication and browser handoff; the [Token authentication plugin](../../host/authentication-token/README.md) contributes its signed entry URL. The `office-kit` row mounts one lazy [Office conversion provider](../../document/office-kit/README.md) for Host consumers, including Desktop compositions using this bundle, and keeps converted files under `$DSH_HOME/office-kit/outputs`. The `standard` and `ptc` presets mount the [Office tools](../../document/tool-office/README.md) in every profile, whether or not Kit is installed, and declare them after an Office skill loads; the `minimal` preset omits them. The conversion service's Remote methods authorize preview reads, while Document Preview owns the Office viewer and Client cache. The `skill-office` row mounts the [Office skills](../../skill/skill-office/README.md) from their packaged assets in every profile. Desktop with a nonempty `DSH_PRIMARY_RUNTIME` also mounts the bundled dependency-query row and selects `pythonEnvironment: 'workspace-dependencies'`; other profiles, and Desktop without a primary runtime, select `pythonEnvironment: 'user'` and leave the dependency-query row disabled. The [Desktop application](../../../apps/desktop/README.md#bundled-workspace-dependencies) owns resource packaging. @@ -120,21 +122,20 @@ Startup display and browser handoff receive the advertised root with its launch ### Readiness -The URL line and browser handoff are readiness signals: supervisors RPC as soon as they observe the line, and a browser requests the page as soon as it opens, so both run only after the Loader tree settles, the required-startup audit passes, and Connection authentication is available — or immediately in a hand-built tree without a Loader. Client combo JavaScript and source maps remain unmaterialized at this point. Optional plugin failures do not suppress readiness; a required startup failure or a tree disposed mid-boot announces nothing. +The URL line and browser handoff are readiness signals: supervisors RPC as soon as they observe the line, and a browser requests the page as soon as it opens, so both run only after the Loader tree settles and the required-startup audit passes — or immediately in a hand-built tree without a Loader. Client combo JavaScript and source maps remain unmaterialized at this point. Optional plugin failures do not suppress readiness; a required startup failure or a tree disposed mid-boot announces nothing. Entry collection passes the ordinary base URL and a mutable entry list; each listener synchronously appends its label, complete URL, and automatic-opening eligibility. Publication runs once per root application; providers that contribute no entry produce no line. ### Source map | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | The `web-app` glue plugin: dist resolution, advertised application URL, bash variable, URL line, browser handoff | +| [`src/index.ts`](src/index.ts) | The `web-app` glue plugin: dist resolution, advertised application URL, bash variable | | [`src/public-url.ts`](src/public-url.ts) | Advertised-root validation and trailing-slash normalization; a leaf module for local imports, not package API | | [`src/startup.ts`](src/startup.ts) | The `web-startup` provider: `--host`, `--port`, `--tls-cert`, `--tls-key`, `--public-url`, `--trusted-host`, `--no-open`, `--help` | | [`cordis.patch.yml`](cordis.patch.yml) | The web patch: restated base values, web host rows, browser roster, preset registry | | [`presets/`](presets) | One `@deepseek-ai/dsh-agent-preset` declaration per shipped preset (`standard`, `ptc`, `minimal`, `cordis`), each its own patch file | -| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | Dist index anchoring, advertised-URL publication and warnings, bash variable, readiness publication | +| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | Dist index anchoring, advertised-URL publication and warnings, bash variable | | [`tests/startup.spec.ts`](tests/startup.spec.ts) | Command-line parsing over a real Loader tree | | [`tests/public-url.spec.ts`](tests/public-url.spec.ts) | Advertised-root parsing and normalization | -| [`tests/browser-open.spec.ts`](tests/browser-open.spec.ts) | Default-browser handoff after the page is reachable |
diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 80b1fd2216..2a617e9f52 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -54,11 +54,13 @@ dsh --profile web --no-open --port 8080 | 字段 | 默认值 | 含义 | |---|---|---| -| `openBrowser` | `true` | 启动后用默认浏览器打开;SSH 启动会抑制它 | -| `printUrl` | `true` | 启动时打印 `dsh web:` URL 行 | +| `printUrl` | `true` | 启动就绪后打印贡献的入口 URL | +| `openBrowser` | `true` | 启动后打开首个允许自动打开的入口,SSH 下除外 | | `surfaceContext` | `true` | 把 `DSH_WEB_URL` 暴露给 agent 的 shell 命令 | | `publicUrl` | 未设置 | 对外公告的 HTTP(S) 应用根;否则公告绑定地址 URL | +WebApp 拥有 `printUrl` 与 `openBrowser`。本组合启用 URL 打印,并把解析后的 `--no-open` 设置传给 runtime。就绪后,同步 `webserver/entry-url` 监听器贡献完整入口。启用打印时,WebApp 按 `label: url` 逐行打印;启用浏览器打开且不在 SSH 下时,仅打开首个 `open: true` 的入口。没有入口则不输出、不打开。 + 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-web-app)列出了本运行时插件接受的字段及其 JSDoc。随发行版交付的组合插入 `schedule` 服务行与 `ui-schedule` 任务页面行,时钟读数与四个提醒工具则属于 `standard`、`cordis` 与 `ptc` 三个 preset。这三个 preset 的 `tool-subagent` 与 `tool-subagent-fork` 两行都 deny 这四个工具,因此被委派子 agent 的作用域不会列出它们。 `standard`、`cordis` 和 `ptc` 三个 preset 在各自的 `tool-subagent-control` 行中设置 `config.interrupt: false`。如需提供 `interrupt_agent`(也适用于 Team 模式),按[迁移步骤](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md)覆盖相应 preset 声明;修改已禁用的 Host 行不会改变 preset 的工具。 @@ -84,7 +86,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- 无论是公告 URL 还是浏览器信任栅栏都不保护端口本身,因此请把端口限制在可信代理或网络内。 -打印的 URL 包含进程凭据,只应与预期用户分享。`printUrl: false` 无论是否配置 `--public-url` 都会抑制该行,凭据也绝不会出现在模型上下文或 `DSH_WEB_URL` 中。 +打印的 URL 包含进程凭据,只应与预期用户分享。WebApp runtime 上的 `printUrl: false` 无论是否配置 `--public-url` 都会抑制该行,凭据也绝不会出现在模型上下文或 `DSH_WEB_URL` 中。 ### 通过 SSH 运行 @@ -106,7 +108,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public-
实现细节——点击展开 -此 bundle 由一层五个文件的补丁和一个运行时胶水插件组成:`cordis.patch.yml` 承载宿主行和 preset 注册表,每个 `presets/.patch.yml` 插入一条随发行版交付的 preset 声明,按 `dsh.bundle.patch` 列出的顺序应用。存储栈与投影缓存来自 `dsh-base`;Web 叠加层的工作区和消息反馈条目消费共享的 `storageDomain` 服务。补丁重述 base 有意省略的界面专用值,插入 Web 专用宿主条目和浏览器插件列表,再将 Agent 层移到预设后面。胶水插件负责 dist 服务、公告应用 URL、明文 HTTP 暴露警告、bash 变量和就绪通知。`office-kit` 条目为宿主消费者挂载一个延迟创建引擎的 [Office 转换提供方](../../document/office-kit/README.zh.md),使用此 bundle 的 Desktop 组合也共享该提供方,转换后的文件保存在 `$DSH_HOME/office-kit/outputs`。`standard` 和 `ptc` 预设在所有 profile 中挂载 [Office 工具](../../document/tool-office/README.zh.md),无论是否安装 Kit,并在加载 Office 技能后声明它们;`minimal` 预设不挂载它们。转换服务的 Remote 方法负责预览读取授权,Document Preview 负责 Office 查看器和客户端缓存。 +此 bundle 由一层五个文件的补丁和一个运行时胶水插件组成:`cordis.patch.yml` 承载宿主行和 preset 注册表,每个 `presets/.patch.yml` 插入一条随发行版交付的 preset 声明,按 `dsh.bundle.patch` 列出的顺序应用。存储栈与投影缓存来自 `dsh-base`;Web 叠加层的工作区和消息反馈条目消费共享的 `storageDomain` 服务。补丁重述 base 有意省略的界面专用值,插入 Web 专用宿主条目和浏览器插件列表,再将 Agent 层移到预设后面。胶水插件负责 dist 服务、公告应用 URL、明文 HTTP 暴露警告和 bash 变量。WebApp 负责启动 URL 发布与浏览器交接;[Token 认证插件](../../host/authentication-token/README.zh.md)贡献带签名的入口 URL。`office-kit` 条目为宿主消费者挂载一个延迟创建引擎的 [Office 转换提供方](../../document/office-kit/README.zh.md),使用此 bundle 的 Desktop 组合也共享该提供方,转换后的文件保存在 `$DSH_HOME/office-kit/outputs`。`standard` 和 `ptc` 预设在所有 profile 中挂载 [Office 工具](../../document/tool-office/README.zh.md),无论是否安装 Kit,并在加载 Office 技能后声明它们;`minimal` 预设不挂载它们。转换服务的 Remote 方法负责预览读取授权,Document Preview 负责 Office 查看器和客户端缓存。 `skill-office` 行在所有 profile 中从包内 assets 挂载 [Office 技能](../../skill/skill-office/README.zh.md)。`DSH_PRIMARY_RUNTIME` 非空的 Desktop 还挂载内置依赖查询行,并选择 `pythonEnvironment: 'workspace-dependencies'`;其他 profile 以及没有主运行时的 Desktop 选择 `pythonEnvironment: 'user'`,并禁用依赖查询行。资源打包由 [Desktop 应用](../../../apps/desktop/README.zh.md#bundled-workspace-dependencies)负责。 @@ -120,21 +122,20 @@ patch 会替换目标行的整个 `config`,因此每个 Web 行都重述自己 ### 就绪宣告 -URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发起 RPC,浏览器一打开就请求页面,因此两者只在 Loader 配置树结算、通过 required 启动检查且 Connection 认证可用后运行——在没有 Loader 的手工构建树中则立即运行。此时 client combo JavaScript 和 source map 仍未物化。可选插件失败不会阻止就绪宣告;required 启动失败或启动中途被释放的树不会宣告任何内容。 +URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发起 RPC,浏览器一打开就请求页面,因此两者只在 Loader 配置树结算并通过 required 启动检查后运行——在没有 Loader 的手工构建树中则立即运行。此时 client combo JavaScript 和 source map 仍未物化。可选插件失败不会阻止就绪宣告;required 启动失败或启动中途被释放的树不会宣告任何内容。入口收集传入普通基地址和可变入口列表;监听器同步追加标签、完整 URL 和自动打开资格。每个根应用仅发布一次;未贡献入口的 Provider 不产生输出行。 ### 源码地图 | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | `web-app` 粘合插件:dist 解析、公告应用 URL、bash 变量、URL 行、浏览器交接 | +| [`src/index.ts`](src/index.ts) | `web-app` 粘合插件:dist 解析、公告应用 URL、bash 变量 | | [`src/public-url.ts`](src/public-url.ts) | 公告根的校验与尾斜杠归一化;供本地导入的叶子模块,不属于包 API | | [`src/startup.ts`](src/startup.ts) | `web-startup` 提供方:`--host`、`--port`、`--tls-cert`、`--tls-key`、`--public-url`、`--trusted-host`、`--no-open`、`--help` | | [`cordis.patch.yml`](cordis.patch.yml) | Web patch:重述的基础值、Web 宿主行、浏览器名录、preset 注册表 | | [`presets/`](presets) | 每个随发行版交付的 preset(`standard`、`ptc`、`minimal`、`cordis`)各一条 `@deepseek-ai/dsh-agent-preset` 声明,各自一个补丁文件 | -| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | dist index 锚定、公告 URL 发布与警告、bash 变量、就绪宣告发布 | +| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | dist index 锚定、公告 URL 发布与警告、bash 变量 | | [`tests/startup.spec.ts`](tests/startup.spec.ts) | 在真实 Loader 树上的命令行解析 | | [`tests/public-url.spec.ts`](tests/public-url.spec.ts) | 公告根的解析与归一化 | -| [`tests/browser-open.spec.ts`](tests/browser-open.spec.ts) | 页面可达后的默认浏览器交接 |
diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 6af70f5ae7..7e6b973a9e 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -193,19 +193,18 @@ # Web glue owned by this bundle: resolves the built frontend dist (an # assembly fact of dsh-web-app, never user config), mounts the - # frontend-static fallback owner, registers the bash runtime variable, - # prints the URL line, and opens the canonical URL after the full Loader - # tree settles and the required-entry audit passes. Invocation-only values - # come from the webStartup provider; the advertised application URL is + # frontend-static fallback owner and registers the bash runtime variable. + # Providers contribute entry URLs; this row owns printing and browser handoff. + # Invocation-only values come from webStartup; the advertised URL is # this row's `publicUrl`, otherwise the bind-address URL. - id: web-runtime name: '@deepseek-ai/dsh-web-app' inject: [webStartup] config: - openBrowser: !!js ctx.webStartup.openBrowser - printUrl: true publicUrl: !!js ctx.webStartup.publicUrl surfaceContext: true + openBrowser: !!js ctx.webStartup.openBrowser + printUrl: true # Model context for an agent that inspects or extends the harness serving # this GUI: value-free prompt sections plus the current checkout and GUI @@ -244,6 +243,9 @@ # The listener's bind IP is accepted separately from this list. trustedHosts: !!js ctx.webStartup.trustedHosts + - id: authentication-token + name: '@deepseek-ai/dsh-host-authentication-token' + # Raw Blob and ReadableStream uploads run independently of Connection's # RPC and generation service. - id: file-upload diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 2959502aa0..718332702c 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -58,6 +58,7 @@ } }, "dependencies": { + "@deepseek-ai/dsh-host-authentication-token": "workspace:*", "@deepseek-ai/dsh-agent-instructions": "workspace:*", "@deepseek-ai/dsh-agent-preset": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", diff --git a/packages/bundle/web-app/src/index.ts b/packages/bundle/web-app/src/index.ts index b93b559620..beffa83b13 100644 --- a/packages/bundle/web-app/src/index.ts +++ b/packages/bundle/web-app/src/index.ts @@ -4,7 +4,7 @@ * manifest field). The plugin owns the browser-surface glue: it resolves * the built frontend dist (workspace knowledge of this bundle, never user * config), mounts the `frontend-static` fallback owner over it, registers the - * bash-visible web runtime variable, the process-token URL line, and the + * bash-visible web runtime variable, the entry URL lines, and the * default-browser handoff, and provides the `webApp` service. An advertised * `publicUrl` replaces the published bind-address URL. Non-loopback * HTTP binds trigger an exposure warning. App command-line values arrive @@ -20,7 +20,7 @@ import z from '@deepseek-ai/schemastery' import { auditStartupEntries } from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-client-connection' import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static' -import { bindUrlHost, isLoopbackHost } from '@deepseek-ai/dsh-host-webserver' +import { bindUrlHost, isLoopbackHost, type WebEntryUrl } from '@deepseek-ai/dsh-host-webserver' import { launchedThroughSsh, launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/cordis-plugin-loader' @@ -55,7 +55,7 @@ export const inject = ['webServer'] export interface Config { /** Permit default-browser handoff after the Loader tree settles; an SSH launch suppresses it. */ openBrowser: boolean - /** Print the URL line on activation; a non-interactive layer can turn it off. */ + /** Print the URL lines on activation; a non-interactive layer can turn them off. */ printUrl: boolean /** * Register the `DSH_WEB_URL` bash variable naming this GUI. A one-shot @@ -143,18 +143,26 @@ function spawnBrowserLauncher(url: string): ChildProcess { } /** Hand one URL to the operating system's default browser. */ -async function openBrowser(url: string): Promise { +async function openBrowser(url: string, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const launcher = spawnBrowserLauncher(url) let launcherStderr = '' launcher.stderr?.setEncoding('utf8') launcher.stderr?.on('data', (chunk: string) => { launcherStderr += chunk }) await new Promise((resolve, reject) => { + const abort = (): void => { launcher.kill() } function onError(error: Error): void { launcher.off('close', onClose) + signal?.removeEventListener('abort', abort) reject(error) } function onClose(code: number | null): void { launcher.off('error', onError) + signal?.removeEventListener('abort', abort) + if (signal?.aborted) { + reject(signal.reason instanceof Error ? signal.reason : new Error('Browser handoff cancelled', { cause: signal.reason })) + return + } if (code !== 0) { const firstLine = launcherStderr.trim().split(/\r?\n/u)[0] const reason = firstLine === undefined || firstLine === '' @@ -168,18 +176,20 @@ async function openBrowser(url: string): Promise { } launcher.once('error', onError) launcher.once('close', onClose) + signal?.addEventListener('abort', abort, { once: true }) + if (signal?.aborted) abort() }) } /** Test hooks for the built dist and native browser handoff; production never mutates them. */ export const internals: { resolveDistIndex: () => string - openBrowser: (url: string) => Promise + openBrowser: (url: string, signal?: AbortSignal) => Promise } = { resolveDistIndex, openBrowser } /** - * Mount the Web runtime: dist serving, the bash runtime variable, the URL - * line, and the default-browser handoff. + * Mount the Web runtime: dist serving, the bash runtime variable, entry URL + * publication, and the default-browser handoff. * @param ctx - plugin context carrying the webServer service. * @param config - validated {@link Config}. */ @@ -216,46 +226,40 @@ export function apply(ctx: Context, config: Config): void { }) } if (config.printUrl || handoffBrowser) { - ctx.inject(['connection'], (connectionCtx) => { - // The URL line and browser handoff are readiness signals: supervisors RPC - // as soon as they observe the line, while a browser requests the page as - // soon as it opens. Neither may run while sibling rows such as the /api - // route owner are still mounting. Await Loader settlement first; a - // hand-built tree without a Loader is already the complete tree. - const announceReady = (): void => { - if (ANNOUNCED_ROOTS.has(connectionCtx.root)) return - const webUrl = appRootUrl() - const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl) - ANNOUNCED_ROOTS.add(connectionCtx.root) - if (config.printUrl) { - console.log(`dsh web: ${authenticatedUrl}`) - } - if (handoffBrowser) { - console.log('dsh web: opening the default browser; pass --no-open to disable') - void internals.openBrowser(authenticatedUrl).catch((error: unknown) => { - const reason = error instanceof Error ? error.message : String(error) - console.error(`web-app: could not open the default browser because ${reason}; use the dsh web URL printed at startup`) - }) - } + const lifetime = new AbortController() + let opening: Promise | undefined + ctx.effect(() => async () => { + lifetime.abort() + await opening + }, 'web-app: startup handoff') + const announceReady = (): void => { + if (lifetime.signal.aborted || ctx.get('webServer') === undefined || ANNOUNCED_ROOTS.has(ctx.root)) return + const entries: WebEntryUrl[] = [] + ctx.emit(ctx.webServer, 'webserver/entry-url', appRootUrl(), entries) + ANNOUNCED_ROOTS.add(ctx.root) + if (config.printUrl) { + for (const entry of entries) console.log(`${entry.label}: ${entry.url}`) } - // This row's own activation can precede a sibling failure. The app owns - // readiness by waiting for its Loader tree, or announces at once in a - // hand-built tree without Loader. - const settled = connectionCtx.get('loader')?.await() - if (settled === undefined) announceReady() - else { - void settled.then(async () => { - await auditStartupEntries(connectionCtx.root, 'dsh web', () => {}) - // The tree can be disposed while the boot was in flight (early - // SIGTERM); a URL line or browser tab for a dead server would only - // mislead, and reading torn-down services would turn a clean shutdown - // into a crash. - if (connectionCtx.get('webServer') !== undefined - && connectionCtx.get('connection') !== undefined) announceReady() - }).catch(() => { - // Boot owns the failure diagnostic; readiness remains unpublished. + const entry = entries.find(entry => entry.open) + if (handoffBrowser && entry !== undefined) { + console.log('dsh web: opening the default browser; pass --no-open to disable') + opening = internals.openBrowser(entry.url, lifetime.signal).catch((error: unknown) => { + if (lifetime.signal.aborted) return + const reason = (error instanceof Error ? error.message : String(error)).replaceAll(entry.url, '[login URL]') + console.error(`web-app: could not open the default browser because ${reason}; use the dsh web URL printed at startup`) }) } - }) + } + const settled = ctx.get('loader')?.await() + if (settled === undefined) announceReady() + else { + void settled.then(async () => { + if (lifetime.signal.aborted) return + await auditStartupEntries(ctx.root, 'dsh web', () => {}) + announceReady() + }).catch(() => { + // The Loader/startup audit owns failure diagnostics; failed startup remains unpublished. + }) + } } } diff --git a/packages/bundle/web-app/tests/browser-launcher.host.spec.ts b/packages/bundle/web-app/tests/browser-launcher.host.spec.ts new file mode 100644 index 0000000000..425a74cdef --- /dev/null +++ b/packages/bundle/web-app/tests/browser-launcher.host.spec.ts @@ -0,0 +1,102 @@ +/** Native browser helper handoff keeps Harness credentials out of the child environment. */ +import { EventEmitter } from 'node:events' +import { spawn, type ChildProcess } from 'node:child_process' +import { PassThrough } from 'node:stream' +import { afterEach, expect, it, vi } from 'vitest' +import { internals } from '../src/index.ts' + +vi.mock('node:child_process', async importOriginal => ({ + ...await importOriginal(), spawn: vi.fn(), +})) +afterEach(() => { vi.restoreAllMocks(); vi.mocked(spawn).mockReset(); vi.unstubAllEnvs() }) + +type BrowserLauncher = ChildProcess & { stderr: PassThrough; kill: ReturnType boolean>> } +function launcher(): BrowserLauncher { + return Object.assign(new EventEmitter(), { stderr: new PassThrough(), kill: vi.fn(() => true) }) as BrowserLauncher +} + +it('scrubs the helper environment and reports spawn or exit failures', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', 'must-not-reach-browser') + vi.stubEnv('DSH_HOME', '/must-not-reach-browser') + const completed = launcher() + vi.mocked(spawn).mockReturnValueOnce(completed) + const completion = internals.openBrowser('http://127.0.0.1:4567') + const [command, args, options] = vi.mocked(spawn).mock.calls[0]! + expect(command).toBe(process.execPath) + expect(args).toEqual(['--input-type=module', '--eval', expect.stringContaining('await import('), '--', 'http://127.0.0.1:4567']) + expect(args?.[2]).toContain("if (process.platform === 'win32')") + expect(args?.[2]).toContain('launcher.ref()') + expect(options?.env).not.toHaveProperty('DEEPSEEK_API_KEY') + expect(options?.env).not.toHaveProperty('DSH_HOME') + expect(options?.env?.PATH).toBe(process.env.PATH) + expect(options?.stdio).toEqual(['ignore', 'inherit', 'pipe']) + completed.emit('close', 0) + await expect(completion).resolves.toBeUndefined() + expect(completed.listenerCount('error')).toBe(0) + + const withStderr = launcher() + vi.mocked(spawn).mockReturnValueOnce(withStderr) + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true) + const withStderrDone = internals.openBrowser('http://127.0.0.1:4567') + withStderr.stderr.write('launcher note\n') + withStderr.emit('close', 0) + await expect(withStderrDone).resolves.toBeUndefined() + expect(stderr).toHaveBeenCalledWith('launcher note\n') + + const detailed = launcher() + vi.mocked(spawn).mockReturnValueOnce(detailed) + const detail = expect(internals.openBrowser('http://127.0.0.1:4567')).rejects.toThrow('desktop unavailable') + detailed.stderr.write('Error: desktop unavailable\n at fixture') + detailed.emit('close', 1) + await detail + + const failed = launcher() + vi.mocked(spawn).mockReturnValueOnce(failed) + const failure = expect(internals.openBrowser('http://127.0.0.1:4567')).rejects.toThrow('exited with code 3') + failed.emit('close', 3) + await failure + + const errored = launcher() + vi.mocked(spawn).mockReturnValueOnce(errored) + const error = expect(internals.openBrowser('http://127.0.0.1:4567')).rejects.toThrow('spawn failed') + errored.emit('error', new Error('spawn failed')) + await error + expect(errored.listenerCount('close')).toBe(0) +}) + +it('stops a helper when cancellation occurs during spawn and retains its non-Error reason', async () => { + const child = launcher() + const controller = new AbortController() + const reason = 'startup scope left' + vi.mocked(spawn).mockImplementationOnce(() => { + controller.abort(reason) + return child + }) + const pending = internals.openBrowser('http://127.0.0.1:4567', controller.signal) + const rejected = expect(pending).rejects.toMatchObject({ message: 'Browser handoff cancelled', cause: reason }) + expect(child.kill).toHaveBeenCalledOnce() + let settled = false + void pending.catch(() => { settled = true }) + await Promise.resolve() + expect(settled).toBe(false) + child.emit('close', null) + await rejected + expect(child.listenerCount('error')).toBe(0) +}) + +it('stops the helper and joins its exit when startup is cancelled', async () => { + const child = launcher() + vi.mocked(spawn).mockReturnValueOnce(child) + const signal = new AbortController() + const reason = new Error('startup scope left') + const pending = internals.openBrowser('http://127.0.0.1:4567', signal.signal) + const rejected = expect(pending).rejects.toBe(reason) + signal.abort(reason) + expect(child.kill).toHaveBeenCalledOnce() + let settled = false + void pending.catch(() => { settled = true }) + await Promise.resolve() + expect(settled).toBe(false) + child.emit('close', null) + await rejected +}) diff --git a/packages/bundle/web-app/tests/browser-open.host.spec.ts b/packages/bundle/web-app/tests/browser-open.host.spec.ts new file mode 100644 index 0000000000..261c0d0da8 --- /dev/null +++ b/packages/bundle/web-app/tests/browser-open.host.spec.ts @@ -0,0 +1,86 @@ +/** WebApp browser startup reaches the authenticated page through a real Loader composition. */ +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context } from '@deepseek-ai/cordis' +import Include from '@deepseek-ai/cordis-plugin-include' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import LocalCredentials from '@deepseek-ai/dsh-credentials-local' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import { auditStartupEntries } from '@deepseek-ai/dsh-app-boot' +import WebServer, { type WebEntryUrl } from '@deepseek-ai/dsh-host-webserver' +import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static' +import { expect, it, onTestFinished, vi } from 'vitest' +import * as Token from '@deepseek-ai/dsh-host-authentication-token' +import * as WebApp from '../src/index.ts' + +it('opens its tokenized URL only after the complete authenticated page is reachable', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-token-browser-open-')) + const ctx = new Context() + const originalOpen = WebApp.internals.openBrowser + const originalResolve = WebApp.internals.resolveDistIndex + onTestFinished(async () => { + await ctx.fiber.dispose() + WebApp.internals.openBrowser = originalOpen + WebApp.internals.resolveDistIndex = originalResolve + vi.unstubAllEnvs() + if (!isAbsolute(root) || dirname(root) !== resolve(tmpdir()) || !basename(root).startsWith('dsh-token-browser-open-')) { + throw new Error(`refusing unexpected fixture cleanup path: ${root}`) + } + await rm(root, { recursive: true, force: true }) + }) + vi.stubEnv('SSH_CONNECTION', '') + vi.stubEnv('SSH_TTY', '') + const dist = join(root, 'dist') + await mkdir(dist) + const index = join(dist, 'index.html') + await writeFile(index, 'token-startup-ready') + const opened = Promise.withResolvers<{ url: string; html: string; peerAccepted: boolean }>() + WebApp.internals.openBrowser = async (url) => { + try { + const login = await fetch(url, { redirect: 'manual' }) + expect(login.status).toBe(303) + expect(login.headers.get('location')).toBe('./') + const cookie = login.headers.get('set-cookie')?.split(';', 1)[0] + if (cookie === undefined) throw new Error('Token startup did not issue a browser Cookie') + const page = await fetch(new URL('./', url), { headers: { cookie } }) + expect(page.status).toBe(200) + const html = await page.text() + const result = ctx.connection.authentication.authenticate({ + headers: { host: new URL(url).host, cookie }, + }) + opened.resolve({ url, html, peerAccepted: 'peer' in result }) + } catch (error) { opened.reject(error) } + } + WebApp.internals.resolveDistIndex = () => index + const rows = [ + { name: 'webserver', config: { host: '127.0.0.1', port: 0 } }, + { name: 'credentials', config: { path: join(root, 'credentials.yaml'), watch: false } }, + { name: 'connection' }, + { name: 'token', config: { cookieMaxAgeDays: 30 } }, + { name: 'web-app', config: { printUrl: false } }, + ] + const config = join(root, 'cordis.yml') + await writeFile(config, rows.map(row => `- ${JSON.stringify({ ...row, name: `cordis:${row.name}` })}`).join('\n') + '\n') + ctx.baseUrl = pathToFileURL(root).href + '/' + await ctx.plugin(Loader) + Object.assign(ctx.loader.builtins, { + include: Include, webserver: WebServer, credentials: LocalCredentials, + connection: Connection, token: Token, frontend: FrontendStatic, + 'web-app': WebApp, + }) + await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(config).href } }) + await ctx.loader.await() + await auditStartupEntries(ctx.root, 'browser-open fixture', () => {}) + const entries: WebEntryUrl[] = [] + ctx.emit(ctx.webServer, 'webserver/entry-url', ctx.webServer.getOrigin(), entries) + expect(entries).toHaveLength(1) + const result = await opened.promise + const url = new URL(result.url) + expect(url.origin).toBe(ctx.webServer.getOrigin()) + expect(url.pathname).toBe('/') + expect(url.searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/u) + expect(result.html).toContain('token-startup-ready') + expect(result.peerAccepted).toBe(true) +}) diff --git a/packages/bundle/web-app/tests/browser-open.spec.ts b/packages/bundle/web-app/tests/browser-open.spec.ts deleted file mode 100644 index bc303e4d21..0000000000 --- a/packages/bundle/web-app/tests/browser-open.spec.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** Default-browser startup over a real Loader tree and listening Web server. */ - -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Context } from '@deepseek-ai/cordis' -import Include from '@deepseek-ai/cordis-plugin-include' -import Loader from '@deepseek-ai/cordis-plugin-loader' -import WebServer from '@deepseek-ai/dsh-host-webserver' -import { apply, internals } from '../src/index.ts' - -const contexts: Context[] = [] -const tempRoots: string[] = [] -const originalResolveDistIndex = internals.resolveDistIndex -const originalOpenBrowser = internals.openBrowser - -beforeEach(() => { - vi.stubEnv('SSH_CONNECTION', '') - vi.stubEnv('SSH_TTY', '') -}) - -afterEach(async () => { - for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() - for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true }) - internals.resolveDistIndex = originalResolveDistIndex - internals.openBrowser = originalOpenBrowser - vi.unstubAllEnvs() - Reflect.deleteProperty(globalThis, '__dshWebAppApply') - Reflect.deleteProperty(globalThis, '__dshWebServer') - Reflect.deleteProperty(globalThis, '__dshConnection') -}) - -describe('web app browser startup', () => { - it('opens the canonical URL only after the complete page is reachable', async () => { - const root = mkdtempSync(join(tmpdir(), 'dsh-web-browser-open-')) - tempRoots.push(root) - const dist = join(root, 'dist') - mkdirSync(dist) - const index = join(dist, 'index.html') - writeFileSync(index, 'ready') - internals.resolveDistIndex = () => index - - const webserverModule = join(root, 'webserver.mjs') - const connectionModule = join(root, 'connection.mjs') - const webAppModule = join(root, 'web-app.mjs') - writeFileSync(webserverModule, 'export default globalThis.__dshWebServer\n') - writeFileSync(connectionModule, [ - "export const inject = ['webServer']", - "export const apply = ctx => ctx.provide('connection', globalThis.__dshConnection)", - '', - ].join('\n')) - writeFileSync(webAppModule, [ - "export const name = 'fixture-web-app'", - "export const inject = ['webServer']", - 'export const apply = (ctx, config) => globalThis.__dshWebAppApply(ctx, config)', - '', - ].join('\n')) - const config = join(root, 'cordis.yml') - writeFileSync(config, [ - '- id: webserver', - ` name: ${pathToFileURL(webserverModule).href}`, - ' config:', - ' host: 127.0.0.1', - ' port: 0', - '- id: connection', - ` name: ${pathToFileURL(connectionModule).href}`, - '- id: web-app', - ` name: ${pathToFileURL(webAppModule).href}`, - ' config:', - ' openBrowser: true', - ' printUrl: false', - ' surfaceContext: false', - '', - ].join('\n')) - - const globals = globalThis as unknown as { - __dshWebAppApply: typeof apply - __dshWebServer: typeof WebServer - __dshConnection: { - authenticatedUrl(baseUrl: string): string - authorizeIndex(): boolean - requestRejection(): undefined - rpc: object - } - } - globals.__dshWebAppApply = apply - globals.__dshWebServer = WebServer - globals.__dshConnection = { - authenticatedUrl: (baseUrl) => { - const url = new URL(baseUrl) - url.searchParams.set('token', 'fixture-token') - return url.href - }, - authorizeIndex: () => true, - requestRejection: () => undefined, - rpc: {}, - } - - let openedUrl: string | undefined - let openedStatus: number | undefined - let resolveOpened!: () => void - const opened = new Promise((resolve) => { resolveOpened = resolve }) - internals.openBrowser = async (url) => { - openedUrl = url - openedStatus = (await fetch(url)).status - resolveOpened() - } - - const ctx = new Context() - contexts.push(ctx) - await ctx.plugin(Loader) - ctx.loader.builtins.include = Include - await ctx.loader.create({ - name: 'cordis:include', - config: { path: pathToFileURL(config).href }, - }) - await ctx.loader.await() - await opened - - expect(openedUrl).toBe(`http://127.0.0.1:${String(ctx.webServer.port)}/?token=fixture-token`) - expect(openedStatus).toBe(200) - }) -}) diff --git a/packages/bundle/web-app/tests/event-isolation.host.spec.ts b/packages/bundle/web-app/tests/event-isolation.host.spec.ts new file mode 100644 index 0000000000..eb730f268f --- /dev/null +++ b/packages/bundle/web-app/tests/event-isolation.host.spec.ts @@ -0,0 +1,66 @@ +/** Published Web entry URLs and source policy stay with their WebServer isolation. */ +import { Context } from '@deepseek-ai/cordis' +import { request as httpRequest, type IncomingMessage, type ServerResponse } from 'node:http' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import WebServer from '@deepseek-ai/dsh-host-webserver' +import { expect, it, onTestFinished, vi } from 'vitest' +import * as WebApp from '../src/index.ts' + +it.each(['main', 'isolated'] as const)('publishes only %s entry URLs and explicit global contributions', async (selected) => { + const ctx = new Context() + const isolated = ctx.isolate('webServer') + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + onTestFinished(async () => { + try { await ctx.fiber.dispose() } finally { log.mockRestore() } + }) + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await isolated.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + ctx.on('webserver/entry-url', function (this: unknown, baseUrl, entries) { + expect(this).toBeInstanceOf(WebServer) + entries.push({ label: 'global', url: `${baseUrl}/global`, open: false }) + }, { global: true }) + ctx.on('webserver/entry-url', (baseUrl, entries) => { + entries.push({ label: 'main', url: `${baseUrl}/main`, open: false }) + }) + isolated.on('webserver/entry-url', (baseUrl, entries) => { + entries.push({ label: 'isolated', url: `${baseUrl}/isolated`, open: false }) + }) + const target = selected === 'main' ? ctx : isolated + const origin = target.webServer.getOrigin() + await target.plugin(WebApp, { printUrl: true, openBrowser: false, surfaceContext: false }).await() + expect(log.mock.calls).toEqual([[`global: ${origin}/global`], [`${selected}: ${origin}/${selected}`]]) +}) + +it('keeps main Connection source checks away from an isolated anonymous webhook route', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const isolated = ctx.isolate('webServer') + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await isolated.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await ctx.plugin(Connection).await() + const mainHandler = vi.fn<(req: IncomingMessage, res: ServerResponse) => void>((_req, res) => { res.end('main') }) + const webhookHandler = vi.fn<(req: IncomingMessage, res: ServerResponse) => void>((req, res) => { res.end(req.headers.host) }) + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/github', auth: 'anonymous', handler: mainHandler })) + isolated.effect(() => isolated.webServer.register({ kind: 'exact', path: '/github', auth: 'anonymous', handler: webhookHandler })) + + const post = (server: WebServer) => new Promise<{ status: number | undefined; body: string }>((resolve, reject) => { + const request = httpRequest(new URL('/github', server.getOrigin()), { + method: 'POST', headers: { host: 'hooks.example.com', connection: 'close' }, + }, (response) => { + let body = '' + response.setEncoding('utf8').on('data', (data: string) => { body += data }) + response.once('end', () => { resolve({ status: response.statusCode, body }) }) + response.once('error', reject) + }) + const closed = new Promise((resolve) => { request.once('close', resolve) }) + onTestFinished(async () => { request.destroy(); await closed }) + request.once('error', reject) + request.end() + }) + const main = await post(ctx.webServer) + expect(main.status).toBe(403) + expect(mainHandler).not.toHaveBeenCalled() + const webhook = await post(isolated.webServer) + expect(webhook).toEqual({ status: 200, body: 'hooks.example.com' }) + expect(webhookHandler).toHaveBeenCalledOnce() +}) diff --git a/packages/bundle/web-app/tests/startup.host.spec.ts b/packages/bundle/web-app/tests/startup.host.spec.ts new file mode 100644 index 0000000000..e162f9d30e --- /dev/null +++ b/packages/bundle/web-app/tests/startup.host.spec.ts @@ -0,0 +1,246 @@ +/** WebApp collects provider entry URLs and owns browser handoff. */ +import { Context } from '@deepseek-ai/cordis' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import * as AppBoot from '@deepseek-ai/dsh-app-boot' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' +import type { WebServer } from '@deepseek-ai/dsh-host-webserver' +import { apply, type Config, internals } from '../src/index.ts' + +const originalOpen = internals.openBrowser +afterEach(() => { internals.openBrowser = originalOpen; vi.restoreAllMocks() }) + +async function setup(options: { origin?: string; ssh?: 'SSH_CONNECTION' | 'SSH_TTY'; settle?: () => Promise } = {}) { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ + { source: 'process', values: options.ssh === undefined ? {} : { [options.ssh]: 'remote-launch' } }, + { source: 'project-env', path: '/project/.env', values: { SSH_TTY: 'project-setting' } }, + ])) + if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [] } as never) + const server: Pick = { + host: '127.0.0.1', protocol: 'http:', registerFallback: () => () => {}, + } + ctx.provide('webServer', server as WebServer) + const baseUrl = () => options.origin ?? 'http://127.0.0.1:3080/' + const auth = { authenticatedUrl: (url: string) => `${url}?token=fixture-token` } + const removeEntry = ctx.on('webserver/entry-url', (url, entries) => { entries.push({ label: 'dsh web', url: auth.authenticatedUrl(url), open: true }) }) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const open = vi.fn<(url: string) => Promise>().mockResolvedValue(undefined) + internals.openBrowser = open + return { ctx, auth, log, error, open, baseUrl, removeEntry } +} + +/** Exercise startup through the same plugin entry as the Loader. */ +function publishStartup(ctx: Context, config: Pick, baseUrl: () => string): void { + apply(ctx, { ...config, publicUrl: baseUrl(), surfaceContext: false }) +} + +it('prints and opens its authenticated advertised URL in order', async () => { + const { ctx, baseUrl, auth, log, open } = await setup({ origin: 'https://public.test/ui/' }) + const events: string[] = [] + log.mockImplementation((value) => { events.push(String(value)) }) + open.mockImplementation((url) => { events.push(`open:${url}`); return Promise.resolve() }) + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + const expected = auth.authenticatedUrl('https://public.test/ui/') + await vi.waitFor(() => { expect(events).toEqual([ + `dsh web: ${expected}`, + 'dsh web: opening the default browser; pass --no-open to disable', + `open:${expected}`, + ]) }) +}) + +it('keeps startup dormant when both flags are disabled', async () => { + const { ctx, baseUrl, log, open } = await setup() + publishStartup(ctx, { printUrl: false, openBrowser: false }, baseUrl) + expect(log).not.toHaveBeenCalled() + expect(open).not.toHaveBeenCalled() +}) + +it.each(['SSH_CONNECTION', 'SSH_TTY'] as const)('prints without opening when %s marks SSH', async (ssh) => { + const remote = await setup({ ssh }) + publishStartup(remote.ctx, { printUrl: true, openBrowser: true }, remote.baseUrl) + await vi.waitFor(() => { expect(remote.log).toHaveBeenCalledWith(`dsh web: ${remote.auth.authenticatedUrl('http://127.0.0.1:3080/')}`) }) + expect(remote.open).not.toHaveBeenCalled() +}) + +it('honors no-open while still printing the login URL', async () => { + const { ctx, baseUrl, log, open } = await setup() + publishStartup(ctx, { printUrl: true, openBrowser: false }, baseUrl) + await vi.waitFor(() => { expect(log).toHaveBeenCalledOnce() }) + expect(open).not.toHaveBeenCalled() +}) + +it('waits for Loader settlement and suppresses a disposed publication', async () => { + const gate = Promise.withResolvers() + const first = await setup({ settle: () => gate.promise }) + const plugin = first.ctx.plugin({ apply(scope: Context) { publishStartup(scope, { printUrl: true, openBrowser: true }, first.baseUrl) } }) + await plugin.await() + expect(first.log).not.toHaveBeenCalled() + await plugin.dispose() + gate.resolve(undefined) + await gate.promise + await Promise.resolve() + expect(first.log).not.toHaveBeenCalled() + expect(first.open).not.toHaveBeenCalled() +}) + +it.each(['disposed', 'unavailable'] as const)('does not publish when startup becomes %s during the audit', async (state) => { + const entered = Promise.withResolvers() + const audited = Promise.withResolvers() + const { ctx, baseUrl, log, open } = await setup({ settle: () => Promise.resolve() }) + vi.spyOn(AppBoot, 'auditStartupEntries').mockImplementation(() => { + entered.resolve(undefined) + return audited.promise + }) + const plugin = ctx.plugin({ apply(scope: Context) { publishStartup(scope, { printUrl: true, openBrowser: true }, baseUrl) } }) + try { + await plugin.await() + await entered.promise + if (state === 'disposed') await plugin.dispose() + else ctx.set('webServer', undefined) + } finally { + audited.resolve(undefined) + await audited.promise + } + expect(log).not.toHaveBeenCalled() + expect(open).not.toHaveBeenCalled() +}) + +it('joins a cancelled browser handoff without reporting it as a launch failure', async () => { + const { ctx, baseUrl, error } = await setup() + const handoff = Promise.withResolvers() + const open = vi.fn(() => handoff.promise) + internals.openBrowser = open + let disposing: Promise | undefined + try { + const plugin = ctx.plugin({ apply(scope: Context) { publishStartup(scope, { printUrl: false, openBrowser: true }, baseUrl) } }) + await plugin.await() + expect(open).toHaveBeenCalledOnce() + const signal = open.mock.calls[0]![1]! + const aborted = new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) + let disposed = false + disposing = plugin.dispose().then(() => { disposed = true }) + await aborted + expect(signal.aborted).toBe(true) + expect(disposed).toBe(false) + } finally { + handoff.reject(new Error('browser handoff cancelled')) + await disposing + } + expect(error).not.toHaveBeenCalled() +}) + +it('publishes after successful Loader settlement', async () => { + const gate = Promise.withResolvers() + const { ctx, baseUrl, auth, log, open } = await setup({ settle: () => gate.promise }) + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + expect(log).not.toHaveBeenCalled() + gate.resolve(undefined) + await vi.waitFor(() => { expect(open).toHaveBeenCalledOnce() }) + expect(log).toHaveBeenCalledWith(`dsh web: ${auth.authenticatedUrl('http://127.0.0.1:3080/')}`) +}) + +it('collects an entry registered while application readiness is pending', async () => { + const gate = Promise.withResolvers() + const { ctx, baseUrl, removeEntry, log, open } = await setup({ settle: () => gate.promise }) + removeEntry() + const collect = vi.fn() + ctx.on('webserver/entry-url', collect) + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + expect(collect).not.toHaveBeenCalled() + ctx.on('webserver/entry-url', (_base, entries) => { + entries.push({ label: 'dsh late', url: 'https://late.test/', open: true }) + }) + gate.resolve(undefined) + await vi.waitFor(() => { expect(open).toHaveBeenCalledOnce() }) + expect(collect).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith('dsh late: https://late.test/') +}) + +it('does not announce failed Loader startup', async () => { + const { ctx, baseUrl, log, open } = await setup({ settle: () => Promise.reject(new Error('loader failed')) }) + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + await Promise.resolve() + await Promise.resolve() + expect(log).not.toHaveBeenCalled() + expect(open).not.toHaveBeenCalled() +}) + +it.each([ + { id: 'webserver', announces: false }, + { id: 'modules', announces: false }, + { id: 'connection', announces: false }, + { id: 'optional-tool', announces: true }, +])('announces=$announces after the $id sibling fails', async ({ id, announces }) => { + const { ctx, baseUrl, log, open } = await setup() + ctx.baseUrl = 'file:///' + await ctx.plugin(Loader) + ctx.loader.builtins.failure = () => { throw new Error('sibling rejected') } + await ctx.loader.root.update([{ id, name: 'cordis:failure' }]) + await ctx.loader.await() + await expect(ctx.loader.resolve(id).fiber?.await()).rejects.toThrow('sibling rejected') + const audit = vi.spyOn(AppBoot, 'auditStartupEntries') + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + await vi.waitFor(() => { expect(audit).toHaveBeenCalledOnce() }) + await Promise.allSettled(audit.mock.results.map(result => result.value as Promise)) + expect(open).toHaveBeenCalledTimes(announces ? 1 : 0) + expect(log).toHaveBeenCalledTimes(announces ? 2 : 0) +}) + +it('publishes at most once across WebApp reloads in the same application', async () => { + const { ctx, baseUrl, log, open } = await setup() + const config = { printUrl: true, openBrowser: true, publicUrl: baseUrl(), surfaceContext: false } + const first = ctx.plugin({ apply }, config) + await first.await() + await first.dispose() + await ctx.plugin({ apply }, config).await() + expect(log).toHaveBeenCalledTimes(2) + expect(open).toHaveBeenCalledOnce() +}) + +it.each([new Error('launcher unavailable'), 'launcher unavailable'])('reports opener failure without disclosing the token: %s', async (failure) => { + const { ctx, baseUrl, auth, error, open } = await setup() + open.mockRejectedValue(failure) + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + await vi.waitFor(() => { expect(error).toHaveBeenCalledOnce() }) + expect(error).toHaveBeenCalledWith('web-app: could not open the default browser because launcher unavailable; use the dsh web URL printed at startup') + expect(error.mock.calls.flat().join(' ')).not.toContain(new URL(auth.authenticatedUrl('http://localhost')).searchParams.get('token')) +}) + + +it('prints all contributed entries and opens only the first eligible entry', async () => { + const { ctx, baseUrl, removeEntry, log, open } = await setup() + removeEntry() + ctx.on('webserver/entry-url', (base, entries) => { + expect(base).toBe(baseUrl()) + entries.push({ label: 'dsh remote', url: 'https://remote.test/invite', open: false }) + }) + ctx.on('webserver/entry-url', (_base, entries) => { + entries.push({ label: 'dsh web', url: 'https://web.test/?token=first', open: true }) + entries.push({ label: 'dsh other', url: 'https://other.test/', open: true }) + }) + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + expect(log.mock.calls.map(call => String(call[0]))).toEqual([ + 'dsh remote: https://remote.test/invite', + 'dsh web: https://web.test/?token=first', + 'dsh other: https://other.test/', + 'dsh web: opening the default browser; pass --no-open to disable', + ]) + expect(open).toHaveBeenCalledOnce() + expect(open).toHaveBeenCalledWith('https://web.test/?token=first', expect.any(AbortSignal)) +}) + +it.each(['absent', 'not-openable'] as const)('does not invent a browser URL when entries are %s', async (mode) => { + const { ctx, baseUrl, removeEntry, log, open } = await setup() + removeEntry() + if (mode === 'not-openable') { + ctx.on('webserver/entry-url', (_base, entries) => { + entries.push({ label: 'dsh remote', url: 'https://remote.test/invite', open: false }) + }) + } + publishStartup(ctx, { printUrl: true, openBrowser: true }, baseUrl) + expect(log).toHaveBeenCalledTimes(mode === 'absent' ? 0 : 1) + expect(open).not.toHaveBeenCalled() +}) diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index 67a350355d..fb2d8820e4 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -1,93 +1,46 @@ -/** Web runtime URL publication, exposure warnings, and Loader/browser handoff readiness. */ - -import { EventEmitter } from 'node:events' -import { spawn, type ChildProcess } from 'node:child_process' +/** Web runtime dist ownership, advertised addresses, exposure warnings, and shell context. */ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import Loader from '@deepseek-ai/cordis-plugin-loader' -import * as AppBoot from '@deepseek-ai/dsh-app-boot' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' import { bindUrlHost, type WebServer } from '@deepseek-ai/dsh-host-webserver' import { apply, Config, internals } from '../src/index.ts' -vi.mock('node:child_process', async importOriginal => ({ - ...await importOriginal(), - spawn: vi.fn(), -})) - let dist: string | undefined - -beforeEach(() => { - vi.stubEnv('SSH_CONNECTION', '') - vi.stubEnv('SSH_TTY', '') -}) +const originalResolve = internals.resolveDistIndex afterEach(() => { vi.restoreAllMocks() - vi.mocked(spawn).mockReset() - vi.unstubAllEnvs() internals.resolveDistIndex = originalResolve - internals.openBrowser = originalOpenBrowser - if (dist !== undefined) rmSync(dist, { recursive: true, force: true }) + if (dist !== undefined) { + if (!isAbsolute(dist) || dirname(dist) !== resolve(tmpdir()) || !basename(dist).startsWith('dsh-web-app-')) { + throw new Error(`refusing unexpected fixture cleanup path: ${dist}`) + } + rmSync(dist, { recursive: true, force: true }) + } dist = undefined }) -const originalResolve = internals.resolveDistIndex -const originalOpenBrowser = internals.openBrowser - -type BrowserLauncher = ChildProcess & { stderr: PassThrough } - -/** Minimal browser-launcher process for the native handoff adapter. */ -function launcher(): BrowserLauncher { - return Object.assign(new EventEmitter(), { stderr: new PassThrough() }) as BrowserLauncher -} - -/** Stage a dist fixture and point the bundle's resolver at it. */ -function stageDist(): string { +/** Supply a distribution owned by this test without invoking a frontend build. */ +function stageDist(): void { dist = mkdtempSync(join(tmpdir(), 'dsh-web-app-')) mkdirSync(join(dist, 'dist')) const index = join(dist, 'dist', 'index.html') writeFileSync(index, 'shell') internals.resolveDistIndex = () => index - return index } -/** Web carrier without a network listener. */ -function fakeHttpServer(host = '127.0.0.1'): { server: WebServer } { +/** Web carrier without a network listener; address formatting follows production. */ +function fakeHttpServer(host = '127.0.0.1', protocol: 'http:' | 'https:' = 'http:'): WebServer { const server: Pick = { - host, - port: 4567, - protocol: 'http:', - getOrigin() { return `http://${bindUrlHost(host) ?? ''}:${String(this.port)}` }, + host, port: 4567, protocol, + getOrigin() { return `${protocol}//${bindUrlHost(host) ?? ''}:${String(this.port)}` }, registerFallback: () => () => {}, renderIndex: (html: string) => html, } - return { server: server as WebServer } -} - -/** Deterministic Host Connection face for URL publication and frontend injection. */ -function provideConnection(ctx: Context): void { - ctx.provide('connection', { - // Adds the process token to the given canonical root, preserving any - // public mount prefix the caller passed. - authenticatedUrl(baseUrl: string) { - const url = new URL(baseUrl) - url.searchParams.set('token', 'test-token') - return url.href - }, - authorizeIndex: () => true, - requestRejection: () => undefined, - rpc: {}, - } as never) -} - -/** A fake Loader whose settlement the test controls (the URL line waits on it). */ -function provideLoader(ctx: Context, settle: () => Promise = async () => {}): void { - ctx.provide('loader', { await: settle, entries: () => [] } as never) + return server as WebServer } interface BashContribution { @@ -96,441 +49,143 @@ interface BashContribution { resolve: () => Record } +function context(host = '127.0.0.1', protocol: 'http:' | 'https:' = 'http:'): Context { + stageDist() + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide('webServer', fakeHttpServer(host, protocol)) + return ctx +} + +function shellContributions(ctx: Context): BashContribution[] { + const contributions: BashContribution[] = [] + ctx.provide('shellEnv', { + register(contribution: BashContribution) { + contributions.push(contribution) + return () => { contributions.splice(contributions.indexOf(contribution), 1) } + }, + } as never) + return contributions +} + describe('web-app runtime glue', () => { it.each([ - '127.0.0.1', - '::ffff:127.0.0.1', - '::ffff:7f00:1', - ])('publishes the URL and surface context for %s before handing it to the browser', async (bind) => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - // Editor markers and a project .env SSH value do not establish a remote launch. - ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([ - { source: 'process', values: { VSCODE_IPC_HOOK_CLI: '/tmp/local-vscode-ipc' } }, - { source: 'project-env', path: '/work/.env', values: { SSH_CONNECTION: 'stale-project-value' } }, - ])) - const { server } = fakeHttpServer(bind) - ctx.provide('webServer', server) - provideConnection(ctx) - const contributions: BashContribution[] = [] - ctx.provide('shellEnv', { - register: (contribution: BashContribution) => { - contributions.push(contribution) - return () => {} - }, - } as never) - provideLoader(ctx) - const lifecycle: string[] = [] - const log = vi.spyOn(console, 'log').mockImplementation((message) => { lifecycle.push(String(message)) }) - const openBrowser = vi.fn(async (url: string) => { lifecycle.push(`open:${url}`) }) - internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) - await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) - - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') - expect(log).toHaveBeenCalledWith('dsh web: opening the default browser; pass --no-open to disable') - expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=test-token') - expect(lifecycle).toEqual([ - 'dsh web: http://127.0.0.1:4567/?token=test-token', - 'dsh web: opening the default browser; pass --no-open to disable', - 'open:http://127.0.0.1:4567/?token=test-token', - ]) - const webRuntime = contributions.find(contribution => contribution.name === 'web-runtime') - expect(webRuntime?.resolve()).toEqual({ DSH_WEB_URL: 'http://127.0.0.1:4567' }) - expect(ctx.webApp.getAdvertisedUrl()).toBe('http://127.0.0.1:4567') - }) - - it('advertises and opens the configured public root behind a prefix-stripping proxy', async () => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - const { server } = fakeHttpServer() - ctx.provide('webServer', server) - provideConnection(ctx) - const contributions: BashContribution[] = [] - ctx.provide('shellEnv', { - register: (contribution: BashContribution) => { - contributions.push(contribution) - return () => {} - }, - } as never) - provideLoader(ctx) - const lifecycle: string[] = [] - vi.spyOn(console, 'log').mockImplementation((message) => { lifecycle.push(String(message)) }) - const openBrowser = vi.fn(async (url: string) => { lifecycle.push(`open:${url}`) }) - internals.openBrowser = openBrowser - apply(ctx, new Config({ - openBrowser: true, - printUrl: true, - surfaceContext: true, - publicUrl: 'https://proxy.example:8443/web', - })) - await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) - - expect(lifecycle).toEqual([ - 'dsh web: https://proxy.example:8443/web/?token=test-token', - 'dsh web: opening the default browser; pass --no-open to disable', - 'open:https://proxy.example:8443/web/?token=test-token', - ]) - const urlContribution = contributions.find(contribution => contribution.name === 'web-runtime') - expect(urlContribution?.resolve()).toEqual({ DSH_WEB_URL: 'https://proxy.example:8443/web/' }) - // The service advertises the row's effective publicUrl, whether it came from --public-url or a profile override. - expect(ctx.webApp.getAdvertisedUrl()).toBe('https://proxy.example:8443/web/') - }) - - it('publishes no readiness side effect when printing and browser opening are disabled', async () => { - stageDist() - const ctx = new Context() - ctx.provide('webServer', fakeHttpServer().server) - provideConnection(ctx) + { mode: 'omitted', enabled: true }, + { mode: 'disabled', enabled: false }, + ])('publishes and opens entries with $mode startup flags', async ({ enabled }) => { + const ctx = context() + ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: {} }])) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const openBrowser = vi.fn(async () => {}) - internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: true })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).not.toHaveBeenCalled() - expect(openBrowser).not.toHaveBeenCalled() - await ctx.fiber.dispose() - }) - - it('skips the surface context when disabled (the one-shot layer): no bash variables', async () => { - stageDist() - const ctx = new Context() - ctx.provide('webServer', fakeHttpServer().server) - provideConnection(ctx) - const contributions: BashContribution[] = [] - ctx.provide('shellEnv', { - register: (contribution: BashContribution) => { - contributions.push(contribution) - return () => {} - }, - } as never) - apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: false })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(contributions).toEqual([]) - await ctx.fiber.dispose() - }) - - it.each([ - { bind: '127.0.0.1', printed: '127.0.0.1' }, - { bind: '::1', printed: '[::1]' }, - { bind: '0:0:0:0:0:ffff:7f08:a', printed: '127.8.0.10' }, - { bind: '::ffff:127.0.0.1%lo', printed: '127.0.0.1' }, - { bind: '::0.0.0.1', printed: '[::1]' }, - { bind: '::0.0.0.1%lo', printed: '[::1]' }, - ])('prints the $bind loopback address without warning or opening a browser', async ({ bind, printed }) => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - ctx.provide('webServer', fakeHttpServer(bind).server) - provideConnection(ctx) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const openBrowser = vi.fn(async () => {}) - internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true })) - await vi.waitFor(() => { expect(log).toHaveBeenCalledWith(`dsh web: http://${printed}:4567/?token=test-token`) }) - expect(warn).not.toHaveBeenCalled() - expect(openBrowser).not.toHaveBeenCalled() - }) - - it.each([ - { bind: '10.1.2.3', printed: '10.1.2.3' }, - // `::127.0.0.1` names the IPv6 address `::7f00:1`, so the tail spelling an - // IPv4 loopback address makes it no loopback bind. - { bind: '::127.0.0.1', printed: '[::7f00:1]' }, - ])('warns and advertises the $bind bind address when the listener is not loopback', async ({ bind, printed }) => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - ctx.provide('webServer', fakeHttpServer(bind).server) - provideConnection(ctx) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const openBrowser = vi.fn(async () => {}) - internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false })) - await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) - - // A non-loopback bind has no loopback listener, so the printed and opened - // root names the bind address; startup warns that the port is plain HTTP. - expect(warn).toHaveBeenCalledTimes(1) - expect(warn).toHaveBeenCalledWith( - `dsh web: listening on ${bind} over plain HTTP; restrict this port to a trusted proxy or network`, - ) - expect(log).toHaveBeenCalledWith(`dsh web: http://${printed}:4567/?token=test-token`) - expect(openBrowser).toHaveBeenCalledWith(`http://${printed}:4567/?token=test-token`) - }) - - - it('drops an IPv6 zone id from the advertised URL', async () => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - // `::1%lo` listens on IPv6 loopback, but a zone id cannot appear in a URL; - // the advertised form must stay a parseable address. - ctx.provide('webServer', fakeHttpServer('::1%lo').server) - provideConnection(ctx) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false })) - await vi.waitFor(() => { expect(log).toHaveBeenCalled() }) - - expect(log).toHaveBeenCalledWith('dsh web: http://[::1]:4567/?token=test-token') - }) - - it.each(['fe80::1%lo', '::127.0.0.1%lo'])('refuses its own activation when %s carries an interface zone id', async (bind) => { - stageDist() - // A zone id cannot appear in a URL, and a non-loopback bind that names one - // has no root this runtime can prove reachable: this row must fail rather - // than let a boot continue without an advertised entry point. - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - ctx.provide('webServer', fakeHttpServer(bind).server) - expect(() => { apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false })) }) - .toThrow(/carries an interface zone id, which no URL can express; pass --public-url/u) - - // A declared root makes the same bind usable. - const declared = new Context() - onTestFinished(() => declared.fiber.dispose()) - declared.provide('webServer', fakeHttpServer(bind).server) - provideConnection(declared) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - apply(declared, new Config({ - openBrowser: false, printUrl: true, surfaceContext: false, publicUrl: 'https://app.example/ui/', - })) - await vi.waitFor(() => { expect(log).toHaveBeenCalled() }) - expect(log).toHaveBeenCalledWith('dsh web: https://app.example/ui/?token=test-token') - }) - - - it('does not publish readiness again when Connection reloads', async () => { - stageDist() - const ctx = new Context() - ctx.provide('webServer', fakeHttpServer().server) - const first = ctx.plugin((connectionCtx: Context) => { provideConnection(connectionCtx) }) - await first - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledTimes(1) - - await first.dispose() - await ctx.plugin((connectionCtx: Context) => { provideConnection(connectionCtx) }) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledTimes(1) - await ctx.fiber.dispose() - }) - - it('advertises the loopback URL when the composition sets publicUrl to null', async () => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - ctx.provide('webServer', fakeHttpServer().server) - provideConnection(ctx) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: false, publicUrl: null as never })) - await vi.waitFor(() => { expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') }) - }) - - it.each([ - ['SSH_CONNECTION', '10.0.0.2 55000 10.0.0.9 22'], - ['SSH_TTY', '/dev/pts/3'], - ] as const)('prints the host URL but skips browser handoff when %s marks an SSH launch', async (name, value) => { - vi.stubEnv(name, value) - stageDist() - const ctx = new Context() - ctx.provide('webServer', fakeHttpServer().server) - provideConnection(ctx) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const openBrowser = vi.fn(async () => {}) - internals.openBrowser = openBrowser - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') - expect(openBrowser).not.toHaveBeenCalled() - await ctx.fiber.dispose() - }) - - it('defers readiness publication until Loader settlement and drops it on failure or teardown', async () => { - stageDist() - const openBrowser = vi.fn(async () => {}) - internals.openBrowser = openBrowser - // Settlement path: both actions wait for loader.await() so their consumers - // can request the complete app immediately. - const settled = new Context() - settled.provide('webServer', fakeHttpServer().server) - provideConnection(settled) - let release: () => void - const settlement = new Promise((resolve) => { release = resolve }) - provideLoader(settled, () => settlement) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - apply(settled, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).not.toHaveBeenCalled() - expect(openBrowser).not.toHaveBeenCalled() - release!() - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') - expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=test-token') - await settled.fiber.dispose() - - // Failed path: Loader reports the sibling failure; the app prints no URL - // for a process that is about to exit. - log.mockClear() - openBrowser.mockClear() - const failed = new Context() - failed.provide('webServer', fakeHttpServer().server) - provideConnection(failed) - provideLoader(failed, async () => { throw new Error('boot failed') }) - apply(failed, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).not.toHaveBeenCalled() - expect(openBrowser).not.toHaveBeenCalled() - await failed.fiber.dispose() - - // Torn-down path: settlement resolves after the webserver is gone — no - // line, no crash. - log.mockClear() - openBrowser.mockClear() - const torn = new Context() - const child = torn.plugin((childCtx: Context) => { - childCtx.provide('webServer', fakeHttpServer().server) - provideConnection(childCtx) + const open = vi.spyOn(internals, 'openBrowser').mockResolvedValue(undefined) + ctx.on('webserver/entry-url', (baseUrl, entries) => { + entries.push({ label: 'dsh web', url: `${baseUrl}/?token=fixture`, open: true }) }) - await child - let releaseTorn: () => void - const tornSettlement = new Promise((resolve) => { releaseTorn = resolve }) - provideLoader(torn, () => tornSettlement) - apply(torn, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) - await new Promise(resolve => setTimeout(resolve, 0)) - await child.dispose() // the webServer service goes away - releaseTorn!() - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).not.toHaveBeenCalled() - expect(openBrowser).not.toHaveBeenCalled() - await torn.fiber.dispose() - }) - - it.each([ - { id: 'webserver', announces: false }, - { id: 'modules', announces: false }, - { id: 'connection', announces: false }, - { id: 'optional-tool', announces: true }, - ])('announces readiness=$announces after the $id sibling fails', async ({ id, announces }) => { - stageDist() - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - ctx.baseUrl = 'file:///' - ctx.provide('webServer', fakeHttpServer().server) - provideConnection(ctx) - await ctx.plugin(Loader) - ctx.loader.builtins.failure = () => { throw new Error('sibling rejected') } - await ctx.loader.root.update([{ id, name: 'cordis:failure' }]) - await ctx.loader.await() - await expect(ctx.loader.resolve(id).fiber?.await()).rejects.toThrow('sibling rejected') - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const openBrowser = vi.fn(async () => {}) - internals.openBrowser = openBrowser - const audit = vi.spyOn(AppBoot, 'auditStartupEntries') - apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false })) - await vi.waitFor(() => { expect(audit).toHaveBeenCalledOnce() }) - await Promise.allSettled(audit.mock.results.map(result => result.value as Promise)) - if (announces) { - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') - expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=test-token') - } else { - expect(log).not.toHaveBeenCalled() - expect(openBrowser).not.toHaveBeenCalled() + const config = enabled ? new Config() : new Config({ surfaceContext: false, printUrl: false, openBrowser: false }) + expect(config).toMatchObject({ printUrl: enabled, openBrowser: enabled }) + apply(ctx, config) + expect(log).toHaveBeenCalledTimes(enabled ? 2 : 0) + expect(open).toHaveBeenCalledTimes(enabled ? 1 : 0) + if (enabled) { + expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=fixture') + expect(open).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=fixture', expect.any(AbortSignal)) + await open.mock.results[0]!.value } }) - it('anchors the dist index on the frontend package manifest without requiring a built dist', () => { - // The production resolver (not the test hook): the anchor resolves on any - // checkout, built or not — dist existence is the fallback owner's - // request-time concern, so a dist-less composition (the static worker - // preview ships its own page) still boots. - expect(originalResolve()).toMatch(/dist[/\\]index\.html$/) + it.each([ + { bind: '127.0.0.1', advertised: '127.0.0.1' }, + { bind: '::1', advertised: '[::1]' }, + { bind: '::ffff:127.0.0.1', advertised: '127.0.0.1' }, + { bind: '::ffff:7f00:1', advertised: '127.0.0.1' }, + { bind: '0:0:0:0:0:ffff:7f08:a', advertised: '127.8.0.10' }, + { bind: '::ffff:127.0.0.1%lo', advertised: '127.0.0.1' }, + { bind: '::0.0.0.1', advertised: '[::1]' }, + { bind: '::0.0.0.1%lo', advertised: '[::1]' }, + { bind: '::1%lo', advertised: '[::1]' }, + ])('advertises $bind and publishes the same clean address to shell context', async ({ bind, advertised }) => { + const ctx = context(bind) + const contributions = shellContributions(ctx) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: true })) + const url = `http://${advertised}:4567` + expect(ctx.webApp.getAdvertisedUrl()).toBe(url) + await vi.waitFor(() => { + expect(contributions.find(item => item.name === 'web-runtime')?.resolve()).toEqual({ DSH_WEB_URL: url }) + }) + expect(warn).not.toHaveBeenCalled() + }) + + it('advertises the configured public root behind a prefix-stripping proxy', async () => { + const ctx = context() + const contributions = shellContributions(ctx) + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: true, publicUrl: 'https://proxy.example:8443/web' })) + expect(ctx.webApp.getAdvertisedUrl()).toBe('https://proxy.example:8443/web/') + await vi.waitFor(() => { + expect(contributions.find(item => item.name === 'web-runtime')?.resolve()).toEqual({ + DSH_WEB_URL: 'https://proxy.example:8443/web/', + }) + }) + }) + + it('skips shell context registration when surface context is disabled', async () => { + const ctx = context() + const contributions = shellContributions(ctx) + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: false })) + const available = Promise.withResolvers() + ctx.inject(['shellEnv'], () => { available.resolve(undefined) }) + await available.promise + expect(contributions).toEqual([]) + expect(ctx.webApp.getAdvertisedUrl()).toBe('http://127.0.0.1:4567') }) it.each([ - ['Error', new Error('no desktop'), 'no desktop'], - ['non-Error', 'desktop unavailable', 'desktop unavailable'], - ] as const)('keeps the server running and reports the manual URL when a browser failure is %s', async (_kind, failure, reason) => { - stageDist() - const ctx = new Context() - ctx.provide('webServer', fakeHttpServer().server) - provideConnection(ctx) - internals.openBrowser = vi.fn(async () => { throw failure }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const diagnostic = vi.spyOn(console, 'error').mockImplementation(() => {}) - apply(ctx, new Config({ openBrowser: true, printUrl: false, surfaceContext: false })) - await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: opening the default browser; pass --no-open to disable') - expect(diagnostic).toHaveBeenCalledWith( - `web-app: could not open the default browser because ${reason}; use the dsh web URL printed at startup`, + { bind: '10.1.2.3', advertised: '10.1.2.3' }, + { bind: '::127.0.0.1', advertised: '[::127.0.0.1]' }, + ])('warns about plaintext exposure and advertises the $bind bind address', ({ bind, advertised }) => { + const ctx = context(bind) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: false })) + expect(ctx.webApp.getAdvertisedUrl()).toBe(`http://${advertised}:4567`) + expect(warn).toHaveBeenCalledExactlyOnceWith( + `dsh web: listening on ${bind} over plain HTTP; restrict this port to a trusted proxy or network`, ) - expect(ctx.get('webServer')).toBeDefined() - await ctx.fiber.dispose() }) - it('scrubs the helper environment and reports helper spawn or exit failures', async () => { - vi.stubEnv('DEEPSEEK_API_KEY', 'must-not-reach-browser') - vi.stubEnv('DSH_HOME', '/must-not-reach-browser') - const completed = launcher() - vi.mocked(spawn).mockReturnValueOnce(completed) - const completion = originalOpenBrowser('http://127.0.0.1:4567') - const [command, args, options] = vi.mocked(spawn).mock.calls[0]! - expect(command).toBe(process.execPath) - expect(args).toEqual([ - '--input-type=module', - '--eval', expect.stringContaining('await import('), - '--', 'http://127.0.0.1:4567', - ]) - expect(args?.[2]).toContain("if (process.platform === 'win32')") - expect(args?.[2]).toContain('launcher.ref()') - expect(options?.env).not.toHaveProperty('DEEPSEEK_API_KEY') - expect(options?.env).not.toHaveProperty('DSH_HOME') - expect(options?.env?.PATH).toBe(process.env.PATH) - expect(options?.stdio).toEqual(['ignore', 'inherit', 'pipe']) - completed.emit('close', 0) - await expect(completion).resolves.toBeUndefined() - expect(completed.listenerCount('error')).toBe(0) + it('keeps the plaintext warning when an HTTPS public URL fronts an HTTP listener', () => { + const ctx = context('10.1.2.3') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: false, publicUrl: 'https://proxy.example/ui/' })) + expect(warn).toHaveBeenCalledOnce() + expect(ctx.webApp.getAdvertisedUrl()).toBe('https://proxy.example/ui/') + }) - const completedWithStderr = launcher() - vi.mocked(spawn).mockReturnValueOnce(completedWithStderr) - const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true) - const completionWithStderr = originalOpenBrowser('http://127.0.0.1:4567') - completedWithStderr.stderr?.write('launcher note\n') - completedWithStderr.emit('close', 0) - await expect(completionWithStderr).resolves.toBeUndefined() - expect(stderr).toHaveBeenCalledWith('launcher note\n') + it('advertises listener TLS without a plaintext warning', () => { + const ctx = context('10.1.2.3', 'https:') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: false })) + expect(ctx.webApp.getAdvertisedUrl()).toBe('https://10.1.2.3:4567') + expect(warn).not.toHaveBeenCalled() + }) - const failedWithReason = launcher() - vi.mocked(spawn).mockReturnValueOnce(failedWithReason) - const reasonFailure = originalOpenBrowser('http://127.0.0.1:4567') - const reasonAssertion = expect(reasonFailure).rejects.toThrow('desktop unavailable') - failedWithReason.stderr?.write('Error: desktop unavailable\n at fixture') - failedWithReason.emit('close', 1) - await reasonAssertion + it.each(['fe80::1%lo', '::127.0.0.1%lo'])('requires publicUrl when %s cannot form an advertised URL', (bind) => { + const ctx = context(bind) + expect(() => { apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: false })) }) + .toThrow(/carries an interface zone id, which no URL can express; pass --public-url/u) + const declared = new Context() + onTestFinished(() => declared.fiber.dispose()) + declared.provide('webServer', fakeHttpServer(bind)) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + apply(declared, new Config({ printUrl: false, openBrowser: false, surfaceContext: false, publicUrl: 'https://app.example/ui/' })) + expect(declared.webApp.getAdvertisedUrl()).toBe('https://app.example/ui/') + }) - const failed = launcher() - vi.mocked(spawn).mockReturnValueOnce(failed) - const failure = originalOpenBrowser('http://127.0.0.1:4567') - const failureAssertion = expect(failure).rejects.toThrow('exited with code 3') - await Promise.resolve() - failed.emit('close', 3) - await failureAssertion + it('uses the bind address when publicUrl is explicitly null', () => { + const ctx = context() + apply(ctx, new Config({ printUrl: false, openBrowser: false, surfaceContext: false, publicUrl: null as never })) + expect(ctx.webApp.getAdvertisedUrl()).toBe('http://127.0.0.1:4567') + }) - const errored = launcher() - vi.mocked(spawn).mockReturnValueOnce(errored) - const error = originalOpenBrowser('http://127.0.0.1:4567') - const errorAssertion = expect(error).rejects.toThrow('spawn failed') - await Promise.resolve() - errored.emit('error', new Error('spawn failed')) - await errorAssertion - expect(errored.listenerCount('close')).toBe(0) + it('anchors the dist index on the frontend package manifest without requiring a built dist', () => { + expect(originalResolve()).toMatch(/dist[/\\]index\.html$/) }) }) diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index c3032532d7..fbd1c96e9b 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -15,11 +15,11 @@ en: 18792bf2fb4f8030 zh: 84c63acc7e0099ae /deepseek-ai-dsh-client-connection/use-this-package: - en: da6810858bf74a86 - zh: d623e510ec74520f + en: 3dc9527a0e2c958b + zh: 7411a438013111af /deepseek-ai-dsh-client-connection/browser-authentication-and-request-trust: - en: e2154aa9caa859b4 - zh: 32832efe4dc37c06 + en: 22e629db9745aae9 + zh: 7004b8b10f2f031d /deepseek-ai-dsh-client-connection/connection-generation: en: d9fe48c025ace7ce zh: 0e23b299fbf25ae6 @@ -30,8 +30,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-connection/known-limitations-and-deferred-work: - en: a860aa95302e4f02 - zh: 4df79a08b5fe018e + en: 58fa6081ac988bad + zh: a81ec93b6e286343 /deepseek-ai-dsh-client-connection/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index e6de487bdb..639e0c531a 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -31,24 +31,26 @@ A static desktop page can provide `__DSH_TRANSPORT__.streamBaseUrl` for the HTTP Unary RPC requests use JSON. A Host handler may return byte attachments that it has already separated from the JSON-compatible result value, with each attachment naming its result-relative path. Connection writes these values as multipart parts. The JSON `metadata` part contains the RPC response envelope with `null` placeholders and an attachment table recording each path, codec, and part identifier. Paths use string keys and numeric array indices; no business field name is reserved. The Client validates the envelope, `rpcId`, attachment table, and parts, then restores each byte value as an `ArrayBuffer`-backed view. Results without attachments, including base64 strings, and failures remain JSON. Logical RPC carriers return decoded native values directly. Connection does not discover binary fields or depend on Typert; the handler that owns a result protocol performs any type-directed or runtime projection before returning. Binary parameters, events, and streamed binary results are unsupported. -The browser uses HTTP POST for Remote unary calls. API Gateway owns the `/api/remote.mux` WebSocket and its logical streams; shell-owned compositions provide equivalent Remote streams, including a stream's uplink, through `connection.rpc.open` without opening a WebSocket. The browser plugin reads the page transport, recovery settings, and location, then delegates to `installConnection(ctx, options)`. A composition that owns its carrier may call the same installer directly; the whole-client test tier does so. Non-page carriers supply `ClientTransportHooks.createWebSocket` with the same authenticated Cookie as HTTP and a `streamBaseUrl`; `ConnectionHandle.openWebSocket()` resolves the Mux path against that base and invokes the selected factory. Each invocation creates one Context-owned service, so several Client trees can use different carriers in one realm. The Host half always provides the carrier-neutral RPC and exact `GET`/`HEAD`/`POST` route registries. When a Web carrier is present it also owns the sole `/api` route, Fetch bridge, browser authentication, and Host/Origin checks; a shell-owned carrier dispatches the shared Fetch handler directly. Each exact route declares buffered or streaming request-body handling before the bridge reads any bytes. Typert Gateway claims generated Remote endpoints, feature packages register non-JSON responses such as Session-log downloads and raw file uploads, and unclaimed requests return 404. Loopback hostname classification remains package-internal to the browser-facing Client state. Browser raw-body transfer is provided by [`dsh-client-file-upload`](../file-upload/README.md). +The browser uses HTTP POST for Remote unary calls. API Gateway owns the `/api/remote.mux` WebSocket and its logical streams; shell-owned compositions provide equivalent Remote streams, including a stream's uplink, through `connection.rpc.open` without opening a WebSocket. The browser plugin reads the page transport, recovery settings, and location, then delegates to `installConnection(ctx, options)`. A composition that owns its carrier may call the same installer directly; the whole-client test tier does so. Non-page carriers supply `ClientTransportHooks.createWebSocket` with the same authenticated Cookie as HTTP and a `streamBaseUrl`; `ConnectionHandle.openWebSocket()` resolves the Mux path against that base and invokes the selected factory. Each invocation creates one Context-owned service, so several Client trees can use different carriers in one realm. The Host half always provides the carrier-neutral RPC and exact `GET`/`HEAD`/`POST` route registries. When a Web carrier is present it also owns the sole `/api` route, Fetch bridge and Host/Origin checks, delegating credential verification to ConnectionAuthentication; a shell-owned carrier dispatches the shared Fetch handler directly. Each exact route declares buffered or streaming request-body handling before the bridge reads any bytes. Typert Gateway claims generated Remote endpoints, feature packages register non-JSON responses such as Session-log downloads and raw file uploads, and unclaimed requests return 404. Loopback hostname classification remains package-internal to the browser-facing Client state. Browser raw-body transfer is provided by [`dsh-client-file-upload`](../file-upload/README.md). ----- ## Browser authentication and request trust -Over the Web carrier, every Host RPC method and WebSocket stream requires an authenticated browser or API Peer; there is no method-specific loopback tier. Each process mints a random launch token. `dsh-web-app` prints and opens its application URL with `?token=...`, preserving the caller's authority and mount; `frontend-static` delegates root and index requests to `ctx.connection.authorizeIndex`, which accepts that token only on `GET /`, writes an authority-bound signed cookie, and redirects to clean `./`, which drops the token and keeps the request's directory. A missing, expired, malformed, or wrong-authority cookie returns 401 before RPC dispatch. Static assets remain public. The HTTP carrier accepts query tokens only at the root exchange and `/connect`, and accepts no Authorization-header token. +Every Host RPC method and WebSocket stream requires an authenticated Peer. The separate [`dsh-host-authentication-token`](../../host/authentication-token/README.md) plugin owns default token verification, Cookie exchange, and signed entry-URL contribution; WebApp owns startup publication. Connection supplies centralized source and credential decisions through synchronous `webserver/authorize`; WebServer enforces each matched route's `auth` and passes the selected Peer directly. `frontend-static` declares authenticated index access and anonymous assets. Anonymous routes skip credential verification but still pass active Connection source checks. -The cookie signing secret is the owner-scoped `client-connection/browser-session` grant record in `ctx.credentials`. The local provider persists it in `$DSH_HOME/.credentials.yaml`; `BrowserAuth` loads or creates the record during Connection activation and retains the secret in memory, so request authentication is synchronous. Deleting or replacing the record takes effect on the next Connection activation. Cookies carry an absolute issue/expiry interval, defaulting to 30 days through `cookieMaxAgeDays`, and bind the normalized hostname plus port in both their deterministic name and signed payload. They are host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`, and carry `Secure` exactly when the listener that received the index request serves TLS; only that listener's own protocol decides, never a `publicUrl` announcement or a forwarded header. +The Host Connection plugin mounts the same-package `ConnectionAuthentication` as the independent nested service `connection.authentication`. Plugins inject `connection.authentication` and register `AuthenticationProvider` objects through `ctx.connection.authentication.register(provider)`. A verifier synchronously returns an existing live `PeerScope` or `undefined`. `connection.authentication.authenticate(request)` returns a `PeerAdmission`, trying registrations in order and using the first success; this credential-only method applies neither HTTP responses nor source policy. An exception permits later providers to succeed; with no success, exceptions produce 503 and ordinary refusals produce 401. Registrations belong to the calling plugin, while Peer ownership stays with its creator. Requests carry no page/API purpose: Token v2 Cookies can authenticate either, and principal plus RemoteAccess determines operation permissions. + +The Token plugin owns the existing `client-connection/browser-session` credential record, Cookie signature, authority binding, lifetime, and TLS attributes. Its `cookieMaxAgeDays` configuration defaults to 30; it loads the signing secret on activation. The Provider registry belongs to ConnectionAuthentication; Token and Cookie algorithms remain inside their Provider. Credential protocols and revocation rules belong to each registered implementation; see the [default Token implementation](../../host/authentication-token/README.md). HTTPS cookie names and signed audiences include the `https:` scheme, so HTTP cookies cannot authenticate to a TLS listener even on the same hostname and port. Default ports normalize under the listener's scheme. Existing HTTP cookie audiences remain unchanged. -Before authentication, every request passes `src/api-request-trust.ts`. Its `Host` must be loopback, equal the listener's bind IP literal on any port, or match a `trustedHosts` entry: exact on `host:port`, any port on port-less entries. Host and configured entries use the listener's scheme for WHATWG default-port normalization, not a forwarded header or `Origin`. An attached HTTP(S) `Origin` must name the same authority, with Host parsed under that Origin's scheme to support HTTPS proxies over HTTP upstreams; `sec-fetch-site: cross-site` is refused. Malformed configured authorities fail plugin load. `allowsRemoteAuthorities` reports whether `trustedHosts` permits a non-loopback authority; accepting the bind IP does not change that list. These checks defend DNS rebinding and cross-site browser requests; they never establish identity. A failed Host/Origin check returns 403, while a trusted but unauthenticated request returns 401. `dsh web --host 0.0.0.0` is unsupported. Decision records: [browser request trust](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [browser token authentication](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md). +For matched `anonymous` and `required` WebServer routes, Connection applies `src/api-request-trust.ts` before any credential verification. `Host` must be loopback, equal the listener's bind IP literal on any port, or match `trustedHosts`: exact for `host:port`, any port for port-less entries. Host and configured entries use the listener's scheme for WHATWG default-port normalization, not forwarded headers or `Origin`. An attached HTTP(S) `Origin` must name the same authority, parsing Host under that Origin's scheme to support HTTPS proxies over HTTP upstreams; `sec-fetch-site: cross-site` is refused. Malformed configured authorities fail plugin load. `allowsRemoteAuthorities` reports whether `trustedHosts` permits a non-loopback authority; accepting the bind IP does not change that list. These checks defend DNS rebinding and cross-site requests, not identity. Rejected sources receive 403 even on anonymous assets or login routes; trusted unauthenticated requests to protected routes receive 401. `dsh web --host 0.0.0.0` is unsupported. Decision records: [browser request trust](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [browser token authentication](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md). -Every request speaks for one Peer, a `PeerScope` whose `principal` names the caller, whose `interactions` governs participation in forwarded events, and whose `signal` aborts when its scope ends. `ctx.connection.browserPeer` is shared by authenticated browser connections; it has owner principal and defaults to `interactions: 'answer'`. `ctx.connection.admit(request)` checks trust and browser or API authentication and returns the credential's live Peer or a rejection. The `/api` route and Gateway WebSocket upgrade use this admission; handlers receive the call's Peer. `ctx.connection.createPeer({ principal, interactions? })` creates an independent in-process Peer, disposed with the Context that read the service or earlier through its own `dispose()`; omitted interactions default to `answer`. The exported `Peer` class accepts the same options. `fetch(request, peer)` and the HTTP bridge take the Peer explicitly; an exact route answers 403 to a non-owner Peer. Method-level access for other principals belongs to [`dsh-api-remote-access`](../../api/remote-access/README.md). +Each authenticated request speaks for a `PeerScope`: `principal` names the caller, `interactions` governs forwarded-event participation, and `signal` aborts when its scope ends. `ctx.connection.browserPeer` remains for trusted in-process callers; network handlers consume WebServer's selected Peer without repeating admission. Direct `ctx.connection.admit(request)` retains source and credential checks for other adapters. `createPeer({ principal, interactions? })` creates a Peer in the calling Context; interactions defaults to `answer`. Connection keeps no Peer lookup table or socket claims; each Provider stores its own Peers. The creator scope or `dispose()` may release a Peer. `fetch(request, peer)` and the HTTP bridge receive the Peer explicitly; exact routes require owner, while method-level decisions belong to [`dsh-api-remote-access`](../../api/remote-access/README.md). -Only API callers use `GET /connect?token=...&interactions=answer|none`: it immediately creates a Peer with owner principal and returns 302 with the Mux destination and a signed API Cookie. The API connection defaults to `none`; invalid or repeated declarations return 400. HTTP may precede WebSocket establishment. One API socket owns cleanup: duplicate attachment returns 409, closure removes its Peer, and later HTTP using that Cookie is refused. Already-admitted unary calls retain request-level cancellation, but `invocation.peer.ctx` cannot register effects after its Peer has been disposed. API callers keep their Cookie separate from browser storage; the authority-specific Cookie name is shared. +The Token plugin owns `GET /connect?token=...&interactions=answer|none` for API callers: it verifies the token, creates an API Peer through Connection, and returns 302 with the Mux destination and a signed API Cookie. The API connection defaults to `none`; invalid or repeated declarations return 400. HTTP may precede WebSocket establishment. Token's `webserver/upgrade` listener owns the API socket claim after route admission: duplicate attachment returns 409, closure synchronously revokes the Cookie before Peer disposal, and later HTTP using it is refused. Other Providers' Peers delegate without Token's single-Socket policy. Already-admitted unary calls retain request-level cancellation, but `invocation.peer.ctx` cannot register effects after its Peer has been disposed. API callers keep their Cookie separate from browser storage; the authority-specific Cookie name is shared. Authenticated shared HTTP requests pass through the `connection/request` waterfall before body transfer. A listener may refuse new requests or await `next()` through response completion; removing its owning fiber removes admission behavior. Desktop uses this hook to lock new API work during an approved installation without canceling already-admitted work. Client disconnection aborts the handler signal; the bridge stops socket writes and drains any remaining response chunks. WebSocket stream ownership remains with API Gateway. @@ -80,7 +82,7 @@ None; this package neither assembles nor sends a provider request. - **Buffered `/api` routes retain each request body in memory** — `maxRequestBodyBytes` (default 300 MiB, sized for the default 200 MiB aggregate image limit after base64 expansion plus envelope headroom) bounds ordinary image and RPC envelopes. Opt-in streaming routes receive backpressured chunks and bypass the aggregate cap; route implementations own persistence, cancellation, and any storage quota. - **A plain-HTTP listener exposes the bearer cookie in transit** — such a deployment cannot mark the browser cookie `Secure`, so serving the same authority over a network can leak the session cookie; configure TLS on the Web carrier ([`dsh-host-webserver`](../../host/webserver/README.md)) to have the cookie marked `Secure` and confined to TLS. - **Unused API Peers may remain until Host shutdown** — no connect deadline or idle collection is imposed on lightweight records whose caller never establishes a WebSocket. Cookie expiry still rejects new requests. API callers must reconnect through `/connect` after their owning socket closes or the Host restarts. -- **There is no logout operation** — clearing the browser cookie ends one browser session; deleting the owner credential record and restarting `dsh` revokes every session. +- **Credential revocation belongs to its Provider** — the default Token plugin's Cookie and logout limits are documented in its [README](../../host/authentication-token/README.md). diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 5b57792975..8831b87472 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -31,24 +31,26 @@ kind: "package-reference" 一元 RPC 请求使用 JSON。Host handler 可以返回已经从 JSON 兼容结果值中分离的字节附件,每个附件标明其相对于结果的路径。Connection 将这些值写为 multipart 部分。JSON `metadata` 部分包含带 `null` 占位值的 RPC 响应信封,以及记录各路径、codec 和部分标识符的附件表。路径使用字符串键与数字数组下标,不保留任何业务字段名。Client 校验信封、`rpcId`、附件表和各部分,再将每个字节值恢复为以 `ArrayBuffer` 为底层缓冲区的视图。没有附件的结果(包括 base64 字符串)与失败仍使用 JSON。逻辑 RPC 载体直接返回解码后的原生值。Connection 不识别二进制字段,也不依赖 Typert;拥有结果协议的 handler 在返回前执行按类型或按运行时值的投影。不支持二进制参数、事件和二进制流式结果。 -浏览器通过 HTTP POST 执行 Remote 一元调用;API Gateway 自己拥有 `/api/remote.mux` WebSocket 及其逻辑流。由 shell 持有的组合通过 `connection.rpc.open` 提供等价的 Remote 流(包括流的上行),不打开 WebSocket。浏览器插件读取页面 transport、恢复设置与 location,再委托 `installConnection(ctx, options)`。持有自身载体的组合可以直接调用同一个安装函数;整机客户端测试档就是这一消费者。非页面载体通过 `ClientTransportHooks.createWebSocket` 使用与 HTTP 相同的认证 Cookie,并提供 `streamBaseUrl`;`ConnectionHandle.openWebSocket()` 根据该 base 解析 Mux 路径,再调用所选工厂。每次调用都会创建一个归所属 Context 的服务,因此同一 realm 中的多棵 Client 树可以使用不同载体。Host half 始终提供与载体无关的 RPC 注册表和精确 `GET`/`HEAD`/`POST` 路由注册表。存在 Web 载体时,它还持有唯一 `/api` route、Fetch bridge、浏览器认证与 Host/Origin 校验;由 shell 持有的载体则直接分派共享 Fetch handler。每条精确路由会在 bridge 读取任何字节前声明缓冲或流式请求体处理方式。Typert Gateway 认领生成的 Remote endpoint,功能包注册 Session 日志下载、原始文件上传等非 JSON 响应,未认领的请求返回 404。Loopback hostname 判定只供浏览器侧当前页面状态使用,留在包内。浏览器原始请求体传输由 [`dsh-client-file-upload`](../file-upload/README.zh.md) 提供。 +浏览器通过 HTTP POST 执行 Remote 一元调用;API Gateway 自己拥有 `/api/remote.mux` WebSocket 及其逻辑流。由 shell 持有的组合通过 `connection.rpc.open` 提供等价的 Remote 流(包括流的上行),不打开 WebSocket。浏览器插件读取页面 transport、恢复设置与 location,再委托 `installConnection(ctx, options)`。持有自身载体的组合可以直接调用同一个安装函数;整机客户端测试档就是这一消费者。非页面载体通过 `ClientTransportHooks.createWebSocket` 使用与 HTTP 相同的认证 Cookie,并提供 `streamBaseUrl`;`ConnectionHandle.openWebSocket()` 根据该 base 解析 Mux 路径,再调用所选工厂。每次调用都会创建一个归所属 Context 的服务,因此同一 realm 中的多棵 Client 树可以使用不同载体。Host half 始终提供与载体无关的 RPC 注册表和精确 `GET`/`HEAD`/`POST` 路由注册表。存在 Web 载体时,它还持有唯一 `/api` route、Fetch bridge 与 Host/Origin 校验,并委托 ConnectionAuthentication 验证凭据;由 shell 持有的载体则直接分派共享 Fetch handler。每条精确路由会在 bridge 读取任何字节前声明缓冲或流式请求体处理方式。Typert Gateway 认领生成的 Remote endpoint,功能包注册 Session 日志下载、原始文件上传等非 JSON 响应,未认领的请求返回 404。Loopback hostname 判定只供浏览器侧当前页面状态使用,留在包内。浏览器原始请求体传输由 [`dsh-client-file-upload`](../file-upload/README.zh.md) 提供。 ----- ## 浏览器认证与请求信任 -通过 Web 载体访问时,每个 Host RPC 方法和 WebSocket 流都要求经过认证的浏览器或 API Peer,不存在按方法区分的 loopback 层。每个进程生成一个随机启动令牌。`dsh-web-app` 打印并打开带 `?token=...` 的应用 URL,保留调用方的 authority 与挂载;`frontend-static` 把根路径和 index 请求交给 `ctx.connection.authorizeIndex`,后者只在 `GET /` 接受该令牌,写入绑定 authority 的签名 cookie,再重定向到干净的 `./`,移除令牌并保留请求目录。缺失、过期、畸形或 authority 不匹配的 cookie 会在 RPC 分发前得到 401。静态资源保持公开。HTTP 载体只在根路径交换与 `/connect` 接受 query token,不接受 Authorization header token。 +每个 Host RPC 方法与 WebSocket 流都要求认证 Peer。独立的 [`dsh-host-authentication-token`](../../host/authentication-token/README.zh.md) 插件拥有默认 Token 验证、Cookie 交换与签名入口 URL 贡献;启动发布归 WebApp。Connection 通过同步 `webserver/authorize` 集中提供来源与凭据决策;WebServer 执行匹配路由的 `auth` 并直接传入选定 Peer。`frontend-static` 声明 index 认证访问及资源匿名访问。匿名路由免凭据验证,但仍经过活动 Connection 的来源检查。 -cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 在 Connection 激活期间加载或创建该记录,并把密钥留在内存中,因此请求认证同步执行。删除或替换该记录会在下一次 Connection 激活时生效。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;收到该 index 请求的监听器提供 TLS 时才带上 `Secure`,且只由该监听器自身的协议决定,`publicUrl` 声明与转发头都不参与判断。 +Host Connection 插件将同包的 `ConnectionAuthentication` 挂载为独立嵌套服务 `connection.authentication`。插件注入 `connection.authentication`,通过 `ctx.connection.authentication.register(provider)` 注册 `AuthenticationProvider` 对象。验证器同步返回已有且存活的 `PeerScope` 或 `undefined`。`connection.authentication.authenticate(request)` 返回 `PeerAdmission`,按注册顺序采用首个成功结果;此方法只验证凭据,不处理 HTTP 响应或来源策略。异常仍允许后续 Provider 成功;全部失败时,有异常返回503,普通拒绝返回401。注册归调用插件,Peer 归创建者。请求不含页面/API purpose;Token v2 Cookie 可认证两者,principal 与 RemoteAccess 决定操作权限。 + +Token 插件拥有既有 `client-connection/browser-session` 凭据记录、Cookie 签名、authority 绑定、有效期与 TLS 属性。它的 `cookieMaxAgeDays` 配置默认为30,在激活时加载签名密钥。Provider 注册表归 ConnectionAuthentication,Token 与 Cookie 算法保留在各自 Provider 内部。凭据协议与撤销规则由各注册实现负责,参见[默认 Token 实现](../../host/authentication-token/README.zh.md)。 HTTPS cookie 名称与签名 audience 包含 `https:` scheme,因此即使 hostname 和 port 相同,HTTP cookie 也无法通过 TLS 监听器的认证。默认端口按监听器的 scheme 归一化。既有 HTTP cookie audience 保持不变。 -认证之前,每个请求都经过 `src/api-request-trust.ts`。其 `Host` 必须是 loopback、等于监听器的绑定 IP 字面量(端口不限),或与 `trustedHosts` 条目匹配:带端口的 `host:port` 精确匹配,不带端口的条目匹配任意端口。Host 与配置条目按监听器的 scheme 做 WHATWG 默认端口归一化,不采信转发 header 或 `Origin`。附带的 HTTP(S) `Origin` 必须指向同一 authority;此时按 Origin 的 scheme 解析 Host,以支持 HTTPS 代理转发到 HTTP 上游;`sec-fetch-site: cross-site` 一律拒绝。畸形配置 authority 会让插件加载失败。`allowsRemoteAuthorities` 报告 `trustedHosts` 是否允许非 loopback authority;接受绑定 IP 不会改变该列表。这些检查防御 DNS rebinding 与跨站浏览器请求,绝不建立身份。Host/Origin 校验失败返回 403;Host 可信但未认证的请求返回 401。`dsh web --host 0.0.0.0` 不受支持。决策记录:[浏览器请求信任](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)与[浏览器令牌认证](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md)。 +对匹配到的 `anonymous` 与 `required` WebServer 路由,Connection 在凭据验证前执行 `src/api-request-trust.ts`。`Host` 必须为回环、等于监听器绑定 IP 字面量(端口不限),或匹配 `trustedHosts`:`host:port` 精确匹配,无端口条目接受任意端口。Host 与配置条目按监听器 scheme 做 WHATWG 默认端口归一化,不采信转发头或 `Origin`。附带 HTTP(S) `Origin` 必须指向同一 authority;按该 Origin 的 scheme 解析 Host,以支持 HTTPS 代理转发到 HTTP 上游;拒绝 `sec-fetch-site: cross-site`。畸形配置 authority 使插件加载失败。`allowsRemoteAuthorities` 表示 `trustedHosts` 是否允许非回环 authority;接受绑定 IP 不改变该列表。这些检查防御 DNS rebinding 与跨站请求,不建立身份。来源拒绝即使在匿名资源或登录路由也返回403;来源可信但未认证访问受保护路由返回401。不支持 `dsh web --host 0.0.0.0`。决策记录:[浏览器请求信任](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)与[浏览器令牌认证](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md)。 -每个请求都代表一个 Peer:`principal` 指明调用方,`interactions` 决定能否参与转发事件,`signal` 在 scope 结束时中止。`ctx.connection.browserPeer` 由通过认证的浏览器连接共享,principal 为 owner,默认 `interactions: 'answer'`。`ctx.connection.admit(request)` 检查信任与浏览器或 API 认证,返回凭据对应的存活 Peer 或拒绝状态;`/api` 路由和 Gateway WebSocket 升级都使用该结果,处理器接收本次调用的 Peer。`ctx.connection.createPeer({ principal, interactions? })` 创建独立进程内 Peer,由读取该服务的 Context 或其自身的 `dispose()` 释放;省略 interactions 时默认 `answer`。导出的 `Peer` 类接受相同参数。`fetch(request, peer)` 和 HTTP bridge 必须显式接收 Peer;对非 owner Peer,exact route 返回 403。其他 principal 的方法级访问归 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md)。 +每个认证请求代表一个 `PeerScope`:`principal` 指明调用方,`interactions` 决定转发事件参与,`signal` 在作用域结束时中止。`ctx.connection.browserPeer` 保留给可信进程内调用方;网络 handler 使用 WebServer 选定的 Peer,不重复准入。直接 `ctx.connection.admit(request)` 为其他适配器保留来源与凭据检查。`createPeer({ principal, interactions? })` 在调用 Context 中创建 Peer;interactions 默认 `answer`。Connection 不维护 Peer 查询表或 Socket 认领;各 Provider 保存自己的 Peer。创建者作用域或 `dispose()` 可释放 Peer。`fetch(request, peer)` 与 HTTP bridge 显式接收 Peer;精确路由要求 owner,方法级判断归 [`dsh-api-remote-access`](../../api/remote-access/README.zh.md)。 -仅供 API 使用的 `GET /connect?token=...&interactions=answer|none` 立即创建 principal 为 owner 的 Peer,返回 302、Mux 目标地址与签名 API Cookie。API 连接默认 `none`,非法或重复声明返回 400。HTTP 可先于 WebSocket 建立。一条 API socket 负责清理:重复关联返回 409,关闭时移除其 Peer,之后使用该 Cookie 的 HTTP 被拒绝。已受理 unary 调用保留请求级取消,但 Peer 释放后 `invocation.peer.ctx` 不再接受新的 effect 注册。API 调用方将 Cookie 与浏览器存储分开;两者使用相同的 authority 专属 Cookie 名称。 +Token 插件拥有供 API 调用方使用的 `GET /connect?token=...&interactions=answer|none`:验证 Token 后通过 Connection 创建 API Peer,返回302、Mux 目标地址和签名 API Cookie。API 连接默认 `none`,非法或重复声明返回 400。HTTP 可先于 WebSocket 建立。Token 的 `webserver/upgrade` 监听器在路由准入后拥有 API Socket 认领:重复关联返回409,关闭时在释放 Peer 前同步撤销 Cookie,之后使用它的 HTTP 被拒绝。其他 Provider 的 Peer 委派后续处理,不应用 Token 的单 Socket 策略。已受理 unary 调用保留请求级取消,但 Peer 释放后 `invocation.peer.ctx` 不再接受新的 effect 注册。API 调用方将 Cookie 与浏览器存储分开;两者使用相同的 authority 专属 Cookie 名称。 通过认证的共享 HTTP 请求在传输请求体之前经过 `connection/request` waterfall。监听器可以拒绝新请求,或等待 `next()` 直到响应完成;释放所属 fiber 会移除准入行为。Desktop 使用此扩展点,在已批准的安装期间锁住新的 API 工作,而不取消已接纳的工作。客户端断开会中止处理函数的信号;桥接器停止写入 socket,并排空剩余响应块。WebSocket 流仍由 API Gateway 负责。 @@ -80,7 +82,7 @@ HTTPS cookie 名称与签名 audience 包含 `https:` scheme,因此即使 host - **缓冲型 `/api` 路由会把每个请求体保留在内存里**:`maxRequestBodyBytes`(默认 300 MiB,按默认 200 MiB 图片总量上限经 base64 膨胀加信封余量得出)限制普通图片与 RPC 信封。显式启用的流式路由接收带背压的分块并绕过总量上限;路由实现负责持久化、取消与存储配额。 - **明文 HTTP 监听器会在传输中暴露 bearer cookie**:此类部署无法给浏览器 cookie 加 `Secure`;若把同一 authority 暴露到网络上,会话 cookie 可能泄露;在 Web 载体([`dsh-host-webserver`](../../host/webserver/README.zh.md))上配置 TLS 即可让 cookie 带上 `Secure` 并只经 TLS 发送。 - **未使用的 API Peer 可以保留到 Host 退出**:调用方从未建立 WebSocket 时,其轻量记录不受建联期限或空闲回收约束。Cookie 过期仍拒绝新请求。其生命周期 socket 关闭或 Host 重启后,API 调用方必须通过 `/connect` 重新接入。 -- **没有 logout 操作**:清除浏览器 cookie 会结束单个浏览器会话;删除 owner 凭据记录并重启 `dsh` 会撤销全部会话。 +- **凭据撤销归其 Provider**:默认 Token 插件的 Cookie 与注销限制记录在其 [README](../../host/authentication-token/README.zh.md)。 diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index 4af79d16ed..2e14b65a0f 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -38,7 +38,6 @@ "license": "MIT", "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-credentials": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "zod": "4.6.6" }, @@ -57,6 +56,8 @@ "@deepseek-ai/dsh-scope": "workspace:*" }, "devDependencies": { + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-host-authentication-token": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index a2fb78ec6c..ed7b92b41b 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -1,5 +1,5 @@ /** - * Browser-trust fence for every /api request. Defends the two confused-deputy + * Browser-trust fence for WebServer routes and direct Connection admission. 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. The Host fence binds every request, @@ -111,7 +111,7 @@ function isBindAddressAuthority(hostUrl: URL, bindHost: string | undefined): boo } /** - * Decide whether one /api request may reach the RPC bridge. + * Decide whether one request satisfies the deployment's source policy. * @param request - Node HTTP or Fetch request facts (headers). * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port. * @param bindHost - the listener's own bind IP literal, accepted on any port independently of `trustedHosts`. diff --git a/packages/client/connection/src/authentication.ts b/packages/client/connection/src/authentication.ts new file mode 100644 index 0000000000..f81e2c7783 --- /dev/null +++ b/packages/client/connection/src/authentication.ts @@ -0,0 +1,73 @@ +/** Ordered credential verification, independent of Connection's transport and source policy. */ +import { Context, Service } from '@deepseek-ai/cordis' +import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import type { AuthenticationProvider, ConnectionTrustRequest, PeerAdmission } from './rpc.ts' + +/** Credential verifier registry whose registrations belong to the calling plugin. */ +export class ConnectionAuthentication extends Service { + private readonly providers = new Set<{ readonly provider: AuthenticationProvider }>() + private readonly owner: Context + private disposed = false + + /** @param ctx - scope owning the credential registry and its lifetime. */ + constructor(ctx: Context) { + super(ctx, 'connection.authentication') + this.owner = ctx + ctx.effect(() => () => { + this.disposed = true + this.providers.clear() + }, 'client-connection: authentication registry') + } + + /** + * Add a credential verifier after the existing registrations. + * @param provider - verifier owning its credential and Peer selection. + * @returns disposer withdrawing this registration; the calling scope also withdraws it on unload. + */ + register(provider: AuthenticationProvider): () => Promise { + return this.ctx.effect(() => { + if (this.disposed || this.owner.fiber.uid === null) throw new Error('connection: authentication registry is disposed') + const entry = { provider } + this.providers.add(entry) + return () => { this.providers.delete(entry) } + }, 'client-connection: authentication provider') + } + + /** + * Verify credentials without applying an HTTP response or source policy. + * @param request - current carrier headers and cancellation facts. + * @returns the first live Peer, 401 if no provider accepts, or 503 when verification failed without success. + */ + authenticate(request: ConnectionTrustRequest): PeerAdmission { + if (this.disposed || this.owner.fiber.uid === null || request.signal?.aborted || request.socket?.destroyed) return { rejection: 401 } + let failed = false + for (const entry of [...this.providers]) { + if (!this.providers.has(entry)) continue + let peer: PeerScope | undefined + try { peer = entry.provider.authenticate(request) } catch (error) { + this.owner.logger.warn('Connection authentication provider failed', error) + failed = true + } + // oxlint-disable-next-line typescript/no-unnecessary-condition -- verification may reenter and dispose the owner. + if (this.disposed || this.owner.fiber.uid === null || request.signal?.aborted || request.socket?.destroyed) return { rejection: 401 } + if (this.providers.has(entry) && peer !== undefined && !peer.signal.aborted) return { peer } + } + return { rejection: failed ? 503 : 401 } + } +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Credential verification shared by Host transports and authentication plugins. */ + 'connection.authentication': ConnectionAuthentication + } +} + +declare module './rpc.ts' { + interface HostConnectionHandle { + /** Credential verifier sub-service; consumers inject `connection.authentication`. */ + readonly authentication: ConnectionAuthentication + } +} + +export default ConnectionAuthentication diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index d563cd40e8..d7ead5c0fb 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -3,31 +3,26 @@ import type { Context } from '@deepseek-ai/cordis' import type { IncomingMessage, ServerResponse } from 'node:http' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-attachment' -import type {} from '@deepseek-ai/dsh-credentials' // Activates the webServer Context merge used below. import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' import { API_PATH } from './api-path.ts' -import { CONNECT_PATH } from './connect-protocol.ts' import { bridge, DEFAULT_MAX_REQUEST_BODY_BYTES } from './http-bridge.ts' import { assertTrustedAuthority } from './api-request-trust.ts' -import { BrowserAuth } from './browser-auth.ts' import { HostConnectionService } from './rpc-host.ts' +import { ConnectionAuthentication } from './authentication.ts' import { ConnectionRecoveryConfigSchema, resolveConnectionConfig, type ConnectionRecoveryConfig } from './recovery-config.ts' export type { + AuthenticationProvider, PeerAdmission, - ConnectionAdmission, ConnectionFetchMethod, ConnectionFetchHandler, ConnectionFetchRoute, - ConnectionIndexRequest, - ConnectionIndexResponse, ConnectionRpcEndpointMatcher, ConnectionRpcAttachment, ConnectionRpcFailure, ConnectionRpcHandler, ConnectionRpcHandlerResult, - ConnectionRequestRejection, ConnectionRpcResult, ConnectionRequestBodyMode, ConnectionTrustRequest, @@ -52,6 +47,7 @@ export { serverResponseSchema, } from './rpc-schema.ts' export { HostConnectionService } from './rpc-host.ts' +export { ConnectionAuthentication } from './authentication.ts' export { API_PATH } from './api-path.ts' @@ -90,7 +86,7 @@ function assertImageBodyCapacity(ctx: Context, maxRequestBodyBytes: number): voi } /** Services required before providing Connection. */ -export const inject = ['credentials'] +export const inject: string[] = [] /** Browser authentication, request limits, and connection recovery configuration. */ export interface ConnectionConfig { @@ -103,8 +99,6 @@ export interface ConnectionConfig { * an entry here. A non-canonical or non-bare authority fails plugin load. */ trustedHosts?: string[] - /** Absolute browser and API cookie lifetime in days. Default: 30. */ - cookieMaxAgeDays?: number /** Maximum buffered JSON body for every `/api` request. Default: 300 MiB. */ maxRequestBodyBytes?: number } @@ -112,56 +106,45 @@ export interface ConnectionConfig { export const Config: z = z.object({ recovery: ConnectionRecoveryConfigSchema.default({}), trustedHosts: z.array(String).default([]), - cookieMaxAgeDays: z.natural().min(1).default(30), maxRequestBodyBytes: z.natural().min(1).default(DEFAULT_MAX_REQUEST_BODY_BYTES), }) /** * Provides carrier-neutral RPC and Fetch registries. When `webServer` is - * present, the plugin also mounts the `/api` browser transport with Host/Origin - * checks and persistent browser authentication. + * present, the plugin applies Host/Origin checks and registered authentication + * to WebServer routes and mounts the `/api` browser transport. * @param ctx - Host plugin context. * @param config - resolved plugin config (schema defaults applied). */ -export async function apply(ctx: Context, config?: ConnectionConfig): Promise { +export function apply(ctx: Context, config?: ConnectionConfig): void { const recovery = resolveConnectionConfig(config?.recovery) // The Loader resolves schema defaults; hand-built test contexts may pass none. const trustedHosts = config?.trustedHosts ?? [] - const cookieMaxAgeDays = config?.cookieMaxAgeDays ?? 30 const maxRequestBodyBytes = config?.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES // Config boundary: a malformed entry fails the load loudly here rather than // silently authorizing its hostname prefix at request time. for (const entry of trustedHosts) assertTrustedAuthority(entry) assertImageBodyCapacity(ctx, maxRequestBodyBytes) - const connection = new HostConnectionService( - ctx, - trustedHosts, - await BrowserAuth.create(ctx.root, ctx.credentials, cookieMaxAgeDays), - ) - ctx.inject(['webServer'], (webCtx) => { - assertImageBodyCapacity(webCtx, maxRequestBodyBytes) - webCtx.on('webserver/index-inject', (table) => { - table.push({ kind: 'global', name: '__DSH_CONNECTION_RECOVERY__', value: recovery }) + new ConnectionAuthentication(ctx) + ctx.inject(['connection.authentication'], (connectionCtx) => { + const connection = new HostConnectionService(connectionCtx, trustedHosts) + connectionCtx.inject(['webServer'], (webCtx) => { + assertImageBodyCapacity(webCtx, maxRequestBodyBytes) + webCtx.on('webserver/index-inject', (table) => { + table.push({ kind: 'global', name: '__DSH_CONNECTION_RECOVERY__', value: recovery }) + }) + const fetchHandler = connection.createSharedFetchHandler(API_PATH) + const route: WebRoute = { + kind: 'prefix', + path: API_PATH, + auth: 'required', + handler: async (req, res, peer) => { + if (peer === undefined || res.destroyed) return + await webCtx.waterfall('connection/request', req, res, () => bridge(req, res, fetchHandler, peer, maxRequestBodyBytes)) + }, + } + webCtx.effect(() => webCtx.webServer.register(route), 'client-connection: /api route') }) - const fetchHandler = connection.createSharedFetchHandler(API_PATH) - const route: WebRoute = { - kind: 'prefix', - path: API_PATH, - handler: async (req, res) => { - const admission = connection.admit(req) - if ('rejection' in admission) { - res.writeHead(admission.rejection) - res.end(admission.rejection === 401 ? 'unauthorized' : 'forbidden') - return - } - await webCtx.waterfall('connection/request', req, res, () => bridge(req, res, fetchHandler, admission.peer, maxRequestBodyBytes)) - }, - } - webCtx.effect(() => webCtx.webServer.register(route), 'client-connection: /api route') - webCtx.effect(() => webCtx.webServer.register({ - kind: 'exact', path: CONNECT_PATH, - handler: (req, res) => { connection.authorizeConnect(req, res) }, - }), 'client-connection: /connect route') }) ctx.inject(['attachments'], (attachmentCtx) => { assertImageBodyCapacity(attachmentCtx, maxRequestBodyBytes) diff --git a/packages/client/connection/src/rpc-host.ts b/packages/client/connection/src/rpc-host.ts index 39e1fc91b0..6801402cde 100644 --- a/packages/client/connection/src/rpc-host.ts +++ b/packages/client/connection/src/rpc-host.ts @@ -2,7 +2,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' -import type { PeerId, PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' +import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' import type { ConnectionInteractions } from './connect-protocol.ts' import { brandString } from '@deepseek-ai/dsh-brand' import type { ClientRequest, RpcId as RpcIdType } from './rpc.ts' @@ -10,13 +10,10 @@ import { clientRequestSchema } from './rpc-schema.ts' import { bridge } from './http-bridge.ts' import { isRemoteAuthority, isTrustedApiRequest } from './api-request-trust.ts' import { API_PATH } from './api-path.ts' -import type { BrowserAuth } from './browser-auth.ts' import { Peer } from './peer.ts' +import type { ConnectionAuthentication } from './authentication.ts' import type { PeerAdmission, - ConnectionAdmission, - ConnectionIndexRequest, - ConnectionIndexResponse, ConnectionFetchRoute, ConnectionFetchHandler, HostConnectionFetch, @@ -24,7 +21,6 @@ import type { ConnectionRpcFailure, ConnectionRpcHandler, ConnectionRpcResult, - ConnectionRequestRejection, ConnectionTrustRequest, HostConnectionHandle, HostConnectionRpc, @@ -34,11 +30,6 @@ const INVALID_REQUEST_RPC_ID = brandString('invalid-request') const CHANNEL_PATTERN = /^\/[A-Za-z0-9._~-]+$/ const ENDPOINT_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/ -interface PeerRecord { - readonly peer: Peer - ownsSocket: boolean -} - interface ConnectionRpcInterceptor { readonly matches: ConnectionRpcEndpointMatcher readonly fetchHandler: ConnectionFetchHandler @@ -65,9 +56,9 @@ declare module '@deepseek-ai/cordis' { /** Host Connection service whose channel registrations belong to the caller fiber. */ export class HostConnectionService extends Service implements HostConnectionHandle { - /** The Peer every authenticated browser connection shares. */ + /** Connection-owned Peer for trusted in-process callers, not network authentication. */ readonly browserPeer: PeerScope - private readonly peers = new Map() + readonly authentication: ConnectionAuthentication private readonly owner: Context private disposed = false private readonly interceptors = new Map() @@ -79,23 +70,29 @@ export class HostConnectionService extends Service implements HostConnectionHand * Provide the Host half over the active HTTP server. * @param ctx - owning Connection plugin context. * @param trustedHosts - deployment authorities accepted by the Host/Origin fence. - * @param browserAuth - process token and persistent browser-session owner. */ constructor( ctx: Context, private readonly trustedHosts: readonly string[], - private readonly browserAuth: BrowserAuth, ) { super(ctx, 'connection') this.owner = ctx + this.authentication = ctx['connection.authentication'] this.browserPeer = new Peer(ctx, { principal: { kind: 'owner' } }) ctx.effect(() => async () => { this.disposed = true - const peers = [this.browserPeer, ...Array.from(this.peers.values(), record => record.peer)] - this.peers.clear() - await Promise.all(peers.map(peer => peer.dispose())) + await this.browserPeer.dispose() }, 'client-connection: Peer scopes') this.allowsRemoteAuthorities = trustedHosts.some(isRemoteAuthority) + ctx.on('webserver/authorize', (request, policy) => { + const facts = { ...request, url: request.url.href } + if (!this.isTrustedRequest(facts)) return { kind: 'deny', status: 403 } + if (policy === 'anonymous') return { kind: 'allow' } + const admission = this.authentication.authenticate(facts) + return 'rejection' in admission + ? { kind: 'deny', status: admission.rejection } + : { kind: 'allow', peer: admission.peer } + }) } /** Generic channel registry scoped to the Context reading this service. */ @@ -116,86 +113,28 @@ export class HostConnectionService extends Service implements HostConnectionHand } } - /** Apply the Host/Origin fence and require an authenticated live Peer. */ - requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection { - const admission = this.admit(request) - return 'rejection' in admission ? admission.rejection : undefined - } - - /** Browser requests share an owner Peer; API HTTP does not depend on an attached socket. */ + /** Apply the carrier source policy and accept the first successful provider. */ admit(request: ConnectionTrustRequest): PeerAdmission { - if (!this.isTrusted(request)) return { rejection: 403 } + if (!this.isTrustedRequest(request)) return { rejection: 403 } if (this.disposed) return { rejection: 401 } - const secure = this.owner.get('webServer')?.protocol === 'https:' - if (this.browserAuth.isAuthenticated(request, secure)) return { peer: this.browserPeer } - const id = this.browserAuth.authenticateApi(request, secure) - const record = id === undefined ? undefined : this.peers.get(id) - return record === undefined ? { rejection: 401 } : { peer: record.peer } + return this.authentication.authenticate(request) } /** Create one in-process Peer owned by the Context that read this service. */ - createPeer(options: { readonly principal: Principal; readonly interactions?: ConnectionInteractions }): PeerScope { + createPeer(options: { + readonly principal: Principal + readonly interactions?: ConnectionInteractions + }): PeerScope { + if (this.disposed) throw new Error('connection: cannot create a Peer after disposal') return new Peer(this.ctx, options) } - /** Claim API socket ownership synchronously; callers release on termination or failed upgrade. */ - admitConnection(request: ConnectionTrustRequest): ConnectionAdmission { - const admission = this.admit(request) - if ('rejection' in admission) return admission - const record = this.peers.get(admission.peer.id) - if (record === undefined) return { ...admission, release: () => Promise.resolve() } - if (record.ownsSocket) return { rejection: 409 } - record.ownsSocket = true - let released: Promise | undefined - return { - peer: record.peer, - release: () => { - if (released !== undefined) return released - this.peers.delete(record.peer.id) - released = record.peer.dispose() - return released - }, - } - } - - private isTrusted(request: ConnectionTrustRequest): boolean { + /** Check the deployment's request-source policy without credential verification. */ + private isTrustedRequest(request: ConnectionTrustRequest): boolean { const carrier = this.owner.get('webServer') return isTrustedApiRequest(request, this.trustedHosts, carrier?.host, carrier?.protocol ?? 'http:') } - private publishPeer(interactions: ConnectionInteractions): PeerId { - const peer = new Peer(this.owner, { principal: { kind: 'owner' }, interactions }) - this.peers.set(peer.id, { peer, ownsSocket: false }) - return peer.id - } - - /** - * Authenticate and publish a credential before sending the connect redirect. - * @param request - launch-token request on /connect. - * @param response - response owned to completion. - */ - authorizeConnect(request: ConnectionIndexRequest, response: ConnectionIndexResponse): void { - if (!this.isTrusted(request) || this.disposed) { - response.writeHead(this.disposed ? 401 : 403) - response.end(this.disposed ? 'unauthorized' : 'forbidden') - return - } - this.browserAuth.authorizeConnect(request, response, - this.owner.get('webServer')?.protocol === 'https:', interactions => this.publishPeer(interactions)) - } - - /** - * Authenticate an index request; native TLS listeners mint Secure cookies. - */ - authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean { - return this.browserAuth.authorizeIndex(request, response, this.ctx.get('webServer')?.protocol === 'https:') - } - - /** Add this process's launch token to the clean application URL. */ - authenticatedUrl(baseUrl: string): string { - return this.browserAuth.authenticatedUrl(baseUrl) - } - /** * Compose one shared-channel Fetch handler from exact routes and its interceptor. * @param channel - shared channel mounted by Connection. @@ -257,20 +196,17 @@ export class HostConnectionService extends Service implements HostConnectionHand const route: WebRoute = { kind: 'prefix', path: channel, - handler: async (req, res) => { - const admission = this.admit(req) - if ('rejection' in admission) { - res.writeHead(admission.rejection) - res.end(admission.rejection === 401 ? 'unauthorized' : 'forbidden') - return - } - await bridge(req, res, fetchHandler, admission.peer) + auth: 'required', + handler: async (req, res, peer) => { + if (peer === undefined || res.destroyed) return + await bridge(req, res, fetchHandler, peer) }, } - return owner.effect( - () => owner.webServer.register(route), - `client-connection: ${channel} rpc channel`, - ) + return owner.effect(() => { + const webServer = owner.get('webServer') + if (webServer === undefined) throw new Error('connection: RPC channels require a WebServer') + return webServer.register(route) + }, `client-connection: ${channel} rpc channel`) } private registerInterceptor( diff --git a/packages/client/connection/src/rpc.ts b/packages/client/connection/src/rpc.ts index aec79d0728..0211698f42 100644 --- a/packages/client/connection/src/rpc.ts +++ b/packages/client/connection/src/rpc.ts @@ -98,36 +98,29 @@ export type RpcMessage = ClientRequest | ServerResponse export interface ConnectionTrustRequest { /** Request headers supplied by either the Fetch or node:http representation. */ readonly headers: Headers | Readonly> -} - -/** HTTP status returned before dispatch, or undefined when the request may proceed. */ -export type ConnectionRequestRejection = 401 | 403 | undefined - -/** Root/index request facts used by the browser-token exchange. */ -export interface ConnectionIndexRequest extends ConnectionTrustRequest { + /** Cancellation of a Fetch request. */ + readonly signal?: AbortSignal | undefined + /** Current disconnection state of a Node carrier. */ + readonly socket?: { readonly destroyed: boolean } | undefined + /** Method and target supplied by the HTTP carrier. */ readonly method?: string | undefined readonly url?: string | undefined } -/** Root/index response operations owned by the browser-token exchange. */ -export interface ConnectionIndexResponse { - writeHead(status: number, headers?: Readonly>): unknown - end(body?: string): unknown +/** A credential verifier returning the existing Peer this request may represent. */ +export interface AuthenticationProvider { + /** + * Verify one request using this implementation's credentials. + * @param request - current request headers and cancellation facts. + * @returns a provider-owned Peer, or undefined to try the next provider. + */ + authenticate(request: ConnectionTrustRequest): PeerScope | undefined } /** Outcome of admitting one request: the Peer it speaks for, or the status refusing it. */ export type PeerAdmission = | { readonly peer: PeerScope } - | { readonly rejection: 401 | 403 } - -/** Socket admission claims API ownership until its carrier calls release, including failed upgrades. */ -export type ConnectionAdmission = - | { - readonly peer: PeerScope - /** Remove and dispose an API Peer; browser releases leave the shared browser Peer intact. */ - readonly release: () => Promise - } - | { readonly rejection: 401 | 403 | 409 } + | { readonly rejection: 401 | 403 | 503 } /** * Handler invoked after Connection has decoded the transport envelope. @@ -208,7 +201,7 @@ export interface HostConnectionHandle { readonly rpc: HostConnectionRpc /** Exact Fetch routes for streaming or browser-native responses. */ readonly fetch: HostConnectionFetch - /** The owner Peer every authenticated browser connection shares. */ + /** Connection-owned Peer for trusted in-process callers, not network authentication. */ readonly browserPeer: PeerScope /** @@ -225,15 +218,7 @@ export interface HostConnectionHandle { createSharedFetchHandler(channel: '/api'): ConnectionFetchHandler /** - * Apply Connection's Host/Origin checks and browser authentication to - * another Web route. - * @param request - request headers from the HTTP or upgrade request. - * @returns rejection status, or undefined when the route may accept the request. - */ - requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection - - /** - * Admit an HTTP request against its signed browser or API credential and live Peer. + * Apply Host/Origin checks and admit the first live Peer returned by a registered credential verifier. * @param request - request headers from the HTTP or upgrade request. * @returns the credential's Peer, or the rejection status. */ @@ -241,36 +226,12 @@ export interface HostConnectionHandle { /** * Create an independent in-process Peer, disposed with the Context that read `ctx.connection`. - * @param options - fixed principal and optional interaction participation (default `answer`). + * @param options - fixed principal and interaction participation (default answer). * @returns a new Peer distinct from every other Peer. */ createPeer(options: { readonly principal: Principal; readonly interactions?: 'answer' | 'none' }): PeerScope - /** - * Claim a physical socket for an API Peer; browser sockets share their owner Peer. - * @param request - authenticated upgrade request headers. - * @returns the Peer and idempotent release, or 409 for duplicate API ownership. - * The carrier releases on socket termination or failed upgrade; release removes - * API admission synchronously without cancelling independent HTTP calls. - */ - admitConnection(request: ConnectionTrustRequest): ConnectionAdmission - /** - * Authenticate one frontend index request, owning a token redirect or 401. - * The cookie this mints is `Secure` when the mounted Web carrier serves TLS, - * which only that listener's protocol decides. - * @param request - root or configured-index HTTP request. - * @param response - response owned when the result is false. - * @returns true only when the frontend may serve index.html. - */ - authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean - - /** - * Add the fresh process token to an ordinary Web application URL. - * @param baseUrl - clean application URL whose authority and mount are preserved. - * @returns tokenized URL for initial login; a mount proxy strips its prefix before {@link authorizeIndex}. - */ - authenticatedUrl(baseUrl: string): string } /** Transport-independent Fetch handler used by HTTP and worker carriers. */ diff --git a/packages/client/connection/tests/authentication.host.spec.ts b/packages/client/connection/tests/authentication.host.spec.ts new file mode 100644 index 0000000000..1414a8bcb9 --- /dev/null +++ b/packages/client/connection/tests/authentication.host.spec.ts @@ -0,0 +1,176 @@ +/** Authentication providers return existing Peers through their independent service. */ +import { Context } from '@deepseek-ai/cordis' +import { afterEach, expect, it, vi } from 'vitest' +import { HostConnectionService } from '../src/rpc-host.ts' +import { ConnectionAuthentication } from '../src/authentication.ts' +import { Peer } from '../src/peer.ts' + +const roots: Context[] = [] +afterEach(async () => { for (const root of roots.splice(0)) await root.fiber.dispose() }) +function setup(): { ctx: Context; connection: HostConnectionService; authentication: ConnectionAuthentication } { + const ctx = new Context() + roots.push(ctx) + const authentication = new ConnectionAuthentication(ctx) + return { ctx, connection: new HostConnectionService(ctx, []), authentication } +} +const request = { headers: { host: 'localhost' } } + +it('requires a WebServer for a physical RPC channel', () => { + const { connection } = setup() + expect(() => connection.rpc.handle('/custom', async () => ({ ok: true, value: null }))) + .toThrow('RPC channels require a WebServer') +}) + +it('checks each request and takes the first live Peer returned by a provider', () => { + const { connection, authentication } = setup() + const first = connection.createPeer({ principal: { kind: 'owner' } }) + const second = connection.createPeer({ principal: { kind: 'owner' } }) + let calls = 0 + authentication.register({ authenticate() { calls++; return undefined } }) + authentication.register({ authenticate() { return first } }) + authentication.register({ authenticate() { throw new Error('should not run') } }) + expect(authentication.authenticate(request)).toEqual({ peer: first }) + expect(authentication.authenticate(request)).toEqual({ peer: first }) + expect(calls).toBe(2) + expect(first).not.toBe(second) +}) + +it('continues after failure and removes a registration through its disposer', async () => { + const { connection, authentication } = setup() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + authentication.register({ authenticate() { throw new Error('unavailable') } }) + const remove = authentication.register({ authenticate: () => peer }) + expect(authentication.authenticate(request)).toEqual({ peer }) + const removing = remove() + expect(authentication.authenticate(request)).toEqual({ rejection: 503 }) + await removing +}) + +it('rejects a cancelled request and skips disposed Peers', async () => { + const { connection, authentication } = setup() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + let calls = 0 + authentication.register({ authenticate() { calls++; return peer } }) + const cancellation = new AbortController() + cancellation.abort() + expect(authentication.authenticate({ ...request, signal: cancellation.signal })).toEqual({ rejection: 401 }) + expect(calls).toBe(0) + await peer.dispose() + expect(authentication.authenticate(request)).toEqual({ rejection: 401 }) +}) + +it('withdraws registrations with their plugin scope while retaining a separately owned Peer', async () => { + const { ctx, connection, authentication } = setup() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + const plugin = ctx.plugin({ + inject: ['connection', 'connection.authentication'], + apply(scope: Context) { + scope.connection.authentication.register({ authenticate: () => peer }) + }, + }) + await plugin.await() + expect(authentication.authenticate(request)).toEqual({ peer }) + await plugin.dispose() + expect(authentication.authenticate(request)).toEqual({ rejection: 401 }) + expect(peer.signal.aborted).toBe(false) +}) + +it('skips a provider withdrawn by an earlier verifier', async () => { + const { connection, authentication } = setup() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + let removing: Promise | undefined + authentication.register({ authenticate() { removing = remove(); return undefined } }) + const authenticate = vi.fn(() => peer) + const remove = authentication.register({ authenticate }) + expect(authentication.authenticate(request)).toEqual({ rejection: 401 }) + expect(authenticate).not.toHaveBeenCalled() + await removing +}) + +it.each(['request', 'socket'] as const)('rejects a %s that ends inside provider verification', (ended) => { + const { connection, authentication } = setup() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + const controller = new AbortController() + const socket = { destroyed: false } + authentication.register({ authenticate() { + if (ended === 'request') controller.abort() + else socket.destroyed = true + return peer + } }) + expect(authentication.authenticate({ ...request, signal: controller.signal, socket })).toEqual({ rejection: 401 }) + expect(peer.signal.aborted).toBe(false) +}) + +it('rejects new work after the Connection owner unloads', async () => { + const ctx = new Context() + roots.push(ctx) + const plugin = ctx.plugin((owner) => { new ConnectionAuthentication(owner); new HostConnectionService(owner, []) }) + await plugin.await() + const connection = ctx.get('connection') as HostConnectionService + const authentication = ctx['connection.authentication'] + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + authentication.register({ authenticate: () => peer }) + await plugin.dispose() + expect(authentication.authenticate(request)).toEqual({ rejection: 401 }) + expect(connection.admit(request)).toEqual({ rejection: 401 }) + expect(() => connection.createPeer({ principal: { kind: 'owner' } })).toThrow('cannot create a Peer after disposal') + expect(() => authentication.register({ authenticate: () => peer })).toThrow('authentication registry is disposed') +}) + +it('ignores a provider withdrawn during its own verification', async () => { + const { connection, authentication } = setup() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + let removing: Promise | undefined + const remove = authentication.register({ authenticate() { removing = remove(); return peer } }) + expect(authentication.authenticate(request)).toEqual({ rejection: 401 }) + await removing +}) + + +it('authenticates without a Connection transport or source policy', () => { + const ctx = new Context() + roots.push(ctx) + const authentication = new ConnectionAuthentication(ctx) + const peer = new Peer(ctx, { principal: { kind: 'owner' } }) + authentication.register({ authenticate: () => peer }) + expect(authentication.name).toBe('connection.authentication') + expect(ctx.get('connectionAuthentication')).toBeUndefined() + expect(ctx.get('connection')).toBeUndefined() + expect(authentication.authenticate({ headers: {} })).toEqual({ peer }) +}) + +it('refuses admission when its service owner is disposed inside verification', async () => { + const ctx = new Context() + roots.push(ctx) + const plugin = ctx.plugin(ConnectionAuthentication) + await plugin.await() + const authentication = ctx['connection.authentication'] + const peer = new Peer(ctx, { principal: { kind: 'owner' } }) + let disposed: Promise | undefined + authentication.register({ authenticate() { + disposed = plugin.dispose() + return peer + } }) + expect(authentication.authenticate(request)).toEqual({ rejection: 401 }) + await disposed + expect(peer.signal.aborted).toBe(false) +}) + +it('withdraws a dependent Connection before its authentication service leaves', async () => { + const ctx = new Context() + roots.push(ctx) + const service = ctx.plugin(ConnectionAuthentication) + await service.await() + const consumer = ctx.plugin({ + inject: ['connection.authentication'], + apply(owner: Context) { new HostConnectionService(owner, []) }, + }) + await consumer.await() + const connection = ctx.connection + const peer = new Peer(ctx, { principal: { kind: 'owner' } }) + ctx['connection.authentication'].register({ authenticate: () => peer }) + expect(connection.admit(request)).toEqual({ peer }) + await service.dispose() + expect(ctx.get('connection')).toBeUndefined() + expect(connection.admit(request)).toEqual({ rejection: 401 }) +}) diff --git a/packages/client/connection/tests/binary-rpc.host.spec.ts b/packages/client/connection/tests/binary-rpc.host.spec.ts index 4431199ec6..ccb37a7d65 100644 --- a/packages/client/connection/tests/binary-rpc.host.spec.ts +++ b/packages/client/connection/tests/binary-rpc.host.spec.ts @@ -3,11 +3,11 @@ import { gunzipSync } from 'node:zlib' import { Context } from '@deepseek-ai/cordis' import WebServer from '@deepseek-ai/dsh-host-webserver' import { describe, expect, it } from 'vitest' -import type { BrowserAuth } from '../src/browser-auth.ts' import { createWebConnectionRpc } from '../src/client/rpc.ts' import { bridge } from '../src/http-bridge.ts' import type { ConnectionRpcHandlerResult, ConnectionRpcResult } from '../src/rpc.ts' import { HostConnectionService } from '../src/rpc-host.ts' +import { ConnectionAuthentication } from '../src/authentication.ts' function binaryResponse(rpcId: string, mutate: (parts: FormData) => void = () => {}): Response { const parts = new FormData() @@ -25,7 +25,7 @@ describe('Connection binary RPC', () => { const ctx = new Context() try { await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0, compression }) - await ctx.plugin((owner) => { new HostConnectionService(owner, [], {} as BrowserAuth) }) + await ctx.plugin((owner) => { new ConnectionAuthentication(owner); new HostConnectionService(owner, []) }) const connection = ctx.get('connection') as HostConnectionService const data = new Uint8Array(1024 * 1024).fill(65) data.set([0, 128, 255]) @@ -35,7 +35,7 @@ describe('Connection binary RPC', () => { attachments: [{ path: ['data'], bytes: data }], })) const handler = connection.createSharedFetchHandler('/api') - ctx.webServer.register({ kind: 'prefix', path: '/api', handler: (req, res) => bridge(req, res, handler, connection.browserPeer) }) + ctx.webServer.register({ kind: 'prefix', path: '/api', auth: 'anonymous', handler: (req, res) => bridge(req, res, handler, connection.browserPeer) }) let transferred = 0 let encoding: string | undefined const rpc = createWebConnectionRpc((path, init) => new Promise((resolve, reject) => { @@ -58,7 +58,14 @@ describe('Connection binary RPC', () => { req.once('error', reject) req.end(init.body as string) })) - expect(await rpc.call('/api', 'fixture/read', {})).toEqual({ ok: true, value: { data, bytes: data.length } }) + const result = await rpc.call('/api', 'fixture/read', {}) + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('binary RPC failed') + const value = result.value as { data: Uint8Array; bytes: number } + expect(Object.keys(value).sort()).toEqual(['bytes', 'data']) + expect(value.bytes).toBe(data.length) + expect(value.data).toBeInstanceOf(Uint8Array) + expect(Buffer.from(value.data).equals(Buffer.from(data))).toBe(true) if (compression === 'gzip') { expect(encoding).toBe('gzip') expect(transferred).toBeLessThan(data.length / 10) @@ -73,7 +80,7 @@ describe('Connection binary RPC', () => { it('roundtrips raw bytes and metadata on the existing channel while JSON results and errors stay JSON', async () => { const ctx = new Context() - const fiber = ctx.plugin((owner) => { new HostConnectionService(owner, [], {} as BrowserAuth) }) + const fiber = ctx.plugin((owner) => { new ConnectionAuthentication(owner); new HostConnectionService(owner, []) }) await fiber.await() try { const connection = ctx.get('connection') as HostConnectionService @@ -133,7 +140,7 @@ describe('Connection binary RPC', () => { it('frames attachments already projected by the result owner', async () => { const ctx = new Context() - const fiber = ctx.plugin((owner) => { new HostConnectionService(owner, [], {} as BrowserAuth) }) + const fiber = ctx.plugin((owner) => { new ConnectionAuthentication(owner); new HostConnectionService(owner, []) }) await fiber.await() try { const connection = ctx.get('connection') as HostConnectionService @@ -186,7 +193,7 @@ describe('Connection binary RPC', () => { it('roundtrips nested, optional and root attachment paths without reserving field names', async () => { const ctx = new Context() - const fiber = ctx.plugin((owner) => { new HostConnectionService(owner, [], {} as BrowserAuth) }) + const fiber = ctx.plugin((owner) => { new ConnectionAuthentication(owner); new HostConnectionService(owner, []) }) await fiber.await() try { const data = new Uint8Array([0, 128, 255]) diff --git a/packages/client/connection/tests/fetch-routes.host.spec.ts b/packages/client/connection/tests/fetch-routes.host.spec.ts index a6b6d159c6..1b85dbe884 100644 --- a/packages/client/connection/tests/fetch-routes.host.spec.ts +++ b/packages/client/connection/tests/fetch-routes.host.spec.ts @@ -1,8 +1,8 @@ import { Context } from '@deepseek-ai/cordis' import type { PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' import { describe, expect, it, vi } from 'vitest' -import type { BrowserAuth } from '../src/browser-auth.ts' import { HostConnectionService } from '../src/rpc-host.ts' +import { ConnectionAuthentication } from '../src/authentication.ts' async function mounted(): Promise<{ readonly connection: HostConnectionService @@ -10,7 +10,7 @@ async function mounted(): Promise<{ }> { const ctx = new Context() const fiber = ctx.plugin((pluginCtx) => { - new HostConnectionService(pluginCtx, [], {} as BrowserAuth) + new ConnectionAuthentication(pluginCtx); new HostConnectionService(pluginCtx, []) }) await fiber.await() return { @@ -147,7 +147,7 @@ describe('Connection in-process Peers', () => { it('disposes a created Peer with the plugin that read the Connection', async () => { const ctx = new Context() - const provider = ctx.plugin((pluginCtx) => { new HostConnectionService(pluginCtx, [], {} as BrowserAuth) }) + const provider = ctx.plugin((pluginCtx) => { new ConnectionAuthentication(pluginCtx); new HostConnectionService(pluginCtx, []) }) await provider.await() let created: PeerScope | undefined const consumer = ctx.plugin({ diff --git a/packages/client/connection/tests/node-half.host.spec.ts b/packages/client/connection/tests/node-half.host.spec.ts index 39c28ab03d..c3a4a368af 100644 --- a/packages/client/connection/tests/node-half.host.spec.ts +++ b/packages/client/connection/tests/node-half.host.spec.ts @@ -1,7 +1,7 @@ /** Node half: registers the /api prefix route bridging to the api gateway. */ -import { EventEmitter } from 'node:events' +import { EventEmitter, once } from 'node:events' import { createServer, request as httpRequest } from 'node:http' -import { Readable } from 'node:stream' +import { PassThrough, Readable } from 'node:stream' import { brandString } from '@deepseek-ai/dsh-brand' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' @@ -22,12 +22,15 @@ import { } from '../src/index.ts' import { DEFAULT_MAX_REQUEST_BODY_BYTES } from '../src/http-bridge.ts' import { provideBrowserCredentials } from './browser-credentials.ts' +import * as Token from '@deepseek-ai/dsh-host-authentication-token' +import { BrowserAuth } from '@deepseek-ai/dsh-host-authentication-token/src/browser-auth.ts' /** The Peer an index render speaks for; this listener reads no field of it. */ const PAGE_PEER = { principal: { kind: 'owner' } } as Parameters[1] /** Structural webServer fake recording both route registries. */ function fakeHttpServer( + ctx: Context, routes: WebRoute[], upgrades: WebUpgradeRoute[], host = '127.0.0.1', @@ -40,8 +43,25 @@ function fakeHttpServer( if (routes.some(candidate => candidate.kind === route.kind && candidate.path === route.path)) { throw new Error(`duplicate route ${route.path}`) } - routes.push(route) - return () => { routes.splice(routes.indexOf(route), 1) } + const registered: WebRoute = { + ...route, + async handler(request, response, peer) { + if (peer !== undefined) return route.handler(request, response, peer) + if (response.destroyed) return + const facts = { headers: request.headers, method: request.method, socket: request.socket, + url: new URL(request.url ?? '/', `${protocol}//localhost`), transport: 'http' as const } + const policy = typeof route.auth === 'function' ? route.auth(facts) : route.auth ?? 'required' + const admission = ctx.bail('webserver/authorize', facts, policy) + if (admission?.kind === 'deny') { + response.writeHead(admission.status) + response.end(admission.status === 401 ? 'unauthorized' : admission.status === 503 ? 'authentication unavailable' : 'forbidden') + return + } + await route.handler(request, response, admission?.peer) + }, + } + routes.push(registered) + return () => { routes.splice(routes.indexOf(registered), 1) } }, registerUpgrade(route) { upgrades.push(route) @@ -55,14 +75,14 @@ function fakeHttpServer( /** Bodyless GET carrying the given headers (enough for the trust fence + bridge). */ function fakeRequest(headers: Record, url = `${API_PATH}/session.list`): IncomingMessage { const request = Readable.from([]) as IncomingMessage - Object.assign(request, { url, method: 'GET', headers }) + Object.assign(request, { url, method: 'GET', headers, socket: { destroyed: false } }) return request } /** JSON POST carrying a complete client-request envelope. */ function fakePost(headers: Record, url: string, body: unknown): IncomingMessage { const request = Readable.from([Buffer.from(JSON.stringify(body))]) as IncomingMessage - Object.assign(request, { url, method: 'POST', headers: { 'content-type': 'application/json', ...headers } }) + Object.assign(request, { url, method: 'POST', headers: { 'content-type': 'application/json', ...headers }, socket: { destroyed: false } }) return request } @@ -99,8 +119,19 @@ function fakeResponse(): { return { response, state } } +async function mountConnection(ctx: Context, config?: ConnectionConfig & { cookieMaxAgeDays?: number }) { + const connection = ctx.plugin({ inject: [...inject], apply }, config) + await connection.await() + const token = ctx.plugin(Token, { cookieMaxAgeDays: config?.cookieMaxAgeDays ?? 30 }) + await token.await() + return { + await: async () => {}, + dispose: async () => { await token.dispose(); await connection.dispose() }, + } +} + async function mounted( - config?: ConnectionConfig, + config?: ConnectionConfig & { cookieMaxAgeDays?: number }, protocol: WebServer['protocol'] = 'http:', credentials?: CredentialProvider, ): Promise<{ @@ -115,8 +146,8 @@ async function mounted( const upgrades: WebUpgradeRoute[] = [] if (credentials === undefined) provideBrowserCredentials(ctx) else ctx.provide('credentials', credentials) - ctx.provide('webServer', fakeHttpServer(routes, upgrades, '127.0.0.1', protocol) as WebServer) - const fiber = ctx.plugin({ inject: [...inject], apply }, config) + ctx.provide('webServer', fakeHttpServer(ctx, routes, upgrades, '127.0.0.1', protocol) as WebServer) + const fiber = await mountConnection(ctx, config) await fiber.await() return { ctx, @@ -127,22 +158,72 @@ async function mounted( } } -/** Exchange a service's process token for one authority-bound Cookie header. */ -function browserCookie(connection: HostConnectionHandle, authority: string): string { - const url = new URL(connection.authenticatedUrl(`http://${authority}`)) +/** Read the test root's token implementation without a production URL service. */ +async function loginUrl(ctx: Context, base: string): Promise { + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + return new URL(auth.authenticatedUrl(base)) +} + +/** Exchange the root token through the owning plugin's HTTP middleware. */ +async function browserCookie(ctx: Context, authority: string): Promise { + const url = await loginUrl(ctx, `http://${authority}`) const exchanged = fakeResponse() - connection.authorizeIndex( - fakeRequest({ host: authority }, `${url.pathname}${url.search}`), - exchanged.response, - ) + await ctx.waterfall('webserver/request', + fakeRequest({ host: authority }, `${url.pathname}${url.search}`), exchanged.response, async () => {}) const setCookie = exchanged.state.headers?.['set-cookie'] if (setCookie === undefined) throw new Error('browser token exchange did not set a cookie') return setCookie.split(';', 1)[0]! } describe('connection node half', () => { + it('reports provider failures on custom RPC routes without writing to a destroyed response', async () => { + const { ctx, connection, routes, dispose } = await mounted() + const handler = vi.fn(async () => ({ ok: true as const, value: null })) + try { + ctx.connection.authentication.register({ authenticate() { throw new Error('provider unavailable') } }) + connection.rpc.handle('/custom', handler) + const route = routes.find(route => route.path === '/custom')! + const failed = fakeResponse() + await route.handler(fakeRequest({ host: 'localhost' }, '/custom/read'), failed.response) + expect(failed.state).toMatchObject({ status: 503, body: 'authentication unavailable' }) + const disconnected = fakeResponse() + Object.assign(disconnected.response, { destroyed: true }) + await route.handler(fakeRequest({ host: 'localhost' }, '/custom/read'), disconnected.response) + expect(disconnected.state).toEqual({}) + expect(handler).not.toHaveBeenCalled() + } finally { + await dispose() + } + }) + + it('dispatches already admitted Peers without checking credentials again', async () => { + const { ctx, connection, routes, dispose } = await mounted() + const peer = connection.createPeer({ principal: { kind: 'owner' } }) + const authenticate = vi.fn(() => undefined) + const handler = vi.fn(async () => ({ ok: true as const, value: null })) + ctx.connection.authentication.register({ authenticate }) + connection.rpc.intercept('/api', () => true, handler) + connection.rpc.handle('/custom', handler) + try { + for (const channel of ['/api', '/custom']) { + const route = routes.find(route => route.path === channel)! + const response = fakeResponse() + await route.handler(fakePost({ host: 'untrusted.example' }, `${channel}/read`, { + type: 'client-request', rpcId: 'admitted', method: 'read', payload: {}, + }), response.response, peer) + expect(response.state.status).toBe(200) + const disconnected = fakeResponse() + Object.assign(disconnected.response, { destroyed: true }) + await route.handler(fakeRequest({ host: 'untrusted.example' }), disconnected.response, peer) + expect(disconnected.state).toEqual({}) + } + expect(authenticate).not.toHaveBeenCalled() + expect(handler).toHaveBeenCalledTimes(2) + } finally { await dispose() } + }) + it('runs request admission after authentication and removes it with its owning fiber', async () => { - const { ctx, routes, connection, dispose } = await mounted() + const { ctx, routes, dispose } = await mounted() let admitted = 0 const guard = ctx.plugin({ apply(owner: Context) { owner.on('connection/request', async (_request, response) => { @@ -157,7 +238,7 @@ describe('connection node half', () => { await routes[0]!.handler(fakeRequest({ host: 'localhost' }), unauthorized.response) expect(unauthorized.state.status).toBe(401) expect(admitted).toBe(0) - const headers = { host: 'localhost', cookie: browserCookie(connection, 'localhost') } + const headers = { host: 'localhost', cookie: await browserCookie(ctx, 'localhost') } const refused = fakeResponse() await routes[0]!.handler(fakeRequest(headers), refused.response) expect(refused.state.status).toBe(503) @@ -189,7 +270,7 @@ describe('connection node half', () => { completed = true }) const response = fakeResponse() - const pending = routes[0]!.handler(fakeRequest({ host: 'localhost', cookie: browserCookie(connection, 'localhost') }, '/api/held'), response.response) + const pending = routes[0]!.handler(fakeRequest({ host: 'localhost', cookie: await browserCookie(ctx, 'localhost') }, '/api/held'), response.response) try { await entered.promise expect(completed).toBe(false) @@ -202,12 +283,19 @@ describe('connection node half', () => { it('provides the carrier-neutral service without a Web server', async () => { const ctx = new Context() provideBrowserCredentials(ctx) - const fiber = ctx.plugin({ inject: [...inject], apply }) + const fiber = await mountConnection(ctx) try { await fiber.await() const connection = ctx.get('connection') as HostConnectionHandle - const cookie = browserCookie(connection, 'localhost') - expect(connection.admit(fakeRequest({ host: 'localhost', cookie }))).toEqual({ peer: connection.browserPeer }) + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + const exchange = fakeResponse() + auth.authorizeIndex(fakeRequest({ host: 'localhost' }, auth.authenticatedUrl('http://localhost/')), exchange.response) + const cookie = exchange.state.headers?.['set-cookie']?.split(';', 1)[0] + if (cookie === undefined) throw new Error('default cookie missing') + const admitted = connection.admit(fakeRequest({ host: 'localhost', cookie })) + if ('rejection' in admitted) throw new Error('carrier-neutral authentication failed') + expect(admitted.peer.principal).toEqual({ kind: 'owner' }) + expect(admitted.peer).not.toBe(connection.browserPeer) } finally { await fiber.dispose() } @@ -218,18 +306,18 @@ describe('connection node half', () => { const routes: WebRoute[] = [] const upgrades: WebUpgradeRoute[] = [] provideBrowserCredentials(ctx) - const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) + const fiber = await mountConnection(ctx, { trustedHosts: ['harness.example'] }) try { await fiber.await() const connection = ctx.get('connection') as HostConnectionHandle const web = ctx.plugin((webCtx) => { - webCtx.provide('webServer', fakeHttpServer(routes, upgrades, '10.1.2.3') as WebServer) + webCtx.provide('webServer', fakeHttpServer(ctx, routes, upgrades, '10.1.2.3') as WebServer) }) try { await web.await() await expect.poll(() => routes.find(route => route.path === API_PATH)).toBeDefined() - const bound = browserCookie(connection, '10.1.2.3:3080') - expect(connection.requestRejection(fakeRequest({ host: '10.1.2.3:3080', cookie: bound }))).toBeUndefined() + const bound = await browserCookie(ctx, '10.1.2.3:3080') + expect(connection.admit(fakeRequest({ host: '10.1.2.3:3080', cookie: bound }))).toHaveProperty('peer') } finally { await web.dispose() } @@ -241,9 +329,9 @@ describe('connection node half', () => { it('uses the TLS default port for markerless exact-authority grants', async () => { const { connection, dispose } = await mounted({ trustedHosts: ['tls.example:443', 'plain.example:80'] }, 'https:') try { - expect(connection.requestRejection(fakeRequest({ host: 'tls.example' }))).toBe(401) - expect(connection.requestRejection(fakeRequest({ host: 'plain.example' }))).toBe(403) - expect(connection.requestRejection(fakeRequest({ host: 'tls.example:444' }))).toBe(403) + expect(connection.admit(fakeRequest({ host: 'tls.example' }))).toEqual({ rejection: 401 }) + expect(connection.admit(fakeRequest({ host: 'plain.example' }))).toEqual({ rejection: 403 }) + expect(connection.admit(fakeRequest({ host: 'tls.example:444' }))).toEqual({ rejection: 403 }) } finally { await dispose() } @@ -251,21 +339,21 @@ describe('connection node half', () => { it('marks the minted browser cookie Secure from the mounted listener protocol', async () => { for (const [protocol, secure] of [['http:', false], ['https:', true]] as const) { - const { connection, dispose } = await mounted(undefined, protocol) + const { ctx, connection, dispose } = await mounted(undefined, protocol) try { - const url = new URL(connection.authenticatedUrl('http://127.0.0.1:3080')) + const url = await loginUrl(ctx, 'http://127.0.0.1:3080') const exchanged = fakeResponse() - connection.authorizeIndex( + await ctx.waterfall('webserver/request', fakeRequest({ host: '127.0.0.1:3080', 'x-forwarded-proto': secure ? 'http' : 'https' }, `${url.pathname}${url.search}`), - exchanged.response, + exchanged.response, async () => {}, ) const setCookie = exchanged.state.headers?.['set-cookie'] expect(setCookie?.endsWith('; Secure'), protocol).toBe(secure) if (setCookie === undefined) throw new Error('browser token exchange did not set a cookie') - expect(connection.requestRejection(fakeRequest({ + expect(connection.admit(fakeRequest({ host: '127.0.0.1:3080', cookie: setCookie.split(';', 1)[0]!, - }))).toBeUndefined() + }))).toHaveProperty('peer') } finally { await dispose() } @@ -295,9 +383,9 @@ describe('connection node half', () => { it.each([ { recovery: { backoffBaseMs: 0 }, error: /backoffBaseMs/ }, { recovery: { backoffFactor: NaN }, error: /backoffFactor.*finite/ }, - ])('rejects invalid recovery timing before acquiring Host resources: $recovery', async ({ recovery, error }) => { + ])('rejects invalid recovery timing before acquiring Host resources: $recovery', ({ recovery, error }) => { const ctx = new Context() - await expect(apply(ctx, { recovery })).rejects.toThrow(error) + expect(() => { apply(ctx, { recovery }) }).toThrow(error) expect(ctx.get('connection')).toBeUndefined() }) @@ -322,15 +410,15 @@ describe('connection node half', () => { expect(DEFAULT_MAX_REQUEST_BODY_BYTES).toBeGreaterThan(Math.ceil(200 * 1024 * 1024 * 4 / 3) + 1024 * 1024) }) - it('fails loud when the carrier cap cannot hold the configured image batch', async () => { + it('fails loud when the carrier cap cannot hold the configured image batch', () => { const ctx = new Context() const routes: WebRoute[] = [] - ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) + ctx.provide('webServer', fakeHttpServer(ctx, routes, []) as WebServer) ctx.provide('attachments', { imageLimits: { maxMessageImageBytes: 20 * 1024 * 1024 }, } as AttachmentStore) - await expect(apply(ctx, { maxRequestBodyBytes: 1024 })) - .rejects.toThrow(/must be at least .* aggregate image limit/) + expect(() => { apply(ctx, { maxRequestBodyBytes: 1024 }) }) + .toThrow(/must be at least .* aggregate image limit/) expect(routes).toHaveLength(0) }) @@ -339,9 +427,8 @@ describe('connection node half', () => { const upgrades: WebUpgradeRoute[] = [] const ctx = new Context() provideBrowserCredentials(ctx) - ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer) - const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.internal/path'] }) - await expect(fiber).rejects.toThrow(/not a bare host\[:port\] authority/) + ctx.provide('webServer', fakeHttpServer(ctx, routes, upgrades) as WebServer) + await expect(mountConnection(ctx, { trustedHosts: ['harness.internal/path'] })).rejects.toThrow(/not a bare host\[:port\] authority/) expect(routes).toHaveLength(0) expect(upgrades).toHaveLength(0) }) @@ -368,7 +455,7 @@ describe('connection node half', () => { }) it('requires the same browser session for every method on every trusted authority', async () => { - const { routes, connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) + const { ctx, routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const methods = [ 'session/openWorkspacePath', 'llm/discoverModels', 'skills/list', 'agentPresets/list', @@ -379,7 +466,7 @@ describe('connection node half', () => { expect([method, denied.state.status, denied.state.body]).toEqual([method, 401, 'unauthorized']) } - const cookie = browserCookie(connection, 'harness.example') + const cookie = await browserCookie(ctx, 'harness.example') for (const method of methods) { const allowed = fakeResponse() await routes[0]!.handler( @@ -396,19 +483,19 @@ describe('connection node half', () => { }) it('passes loopback and declared-authority requests through to the bridge', async () => { - const { routes, connection, dispose } = await mounted({ trustedHosts: ['harness.example:3080', '192.168.1.5'] }) + const { ctx, routes, dispose } = await mounted({ trustedHosts: ['harness.example:3080', '192.168.1.5'] }) // 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', - cookie: browserCookie(connection, '127.0.0.1:3080'), + cookie: await browserCookie(ctx, '127.0.0.1:3080'), }), loopback.response) expect(loopback.state.status).toBe(404) const lan = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '192.168.1.5:3080', - cookie: browserCookie(connection, '192.168.1.5:3080'), + cookie: await browserCookie(ctx, '192.168.1.5:3080'), }), lan.response) expect(lan.state.status).toBe(404) // Declared public authority, same-origin browser shape. @@ -417,23 +504,23 @@ describe('connection node half', () => { host: 'harness.example:3080', origin: 'http://harness.example:3080', 'sec-fetch-site': 'same-origin', - cookie: browserCookie(connection, 'harness.example:3080'), + cookie: await browserCookie(ctx, 'harness.example:3080'), }), declared.response) expect(declared.state.status).toBe(404) await dispose() }) it('shares its configured trust and authentication policy with sibling routes', async () => { - const { connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) + const { ctx, connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const loopback = fakeRequest({ host: '127.0.0.1:3080' }) const declared = fakeRequest({ host: 'harness.example' }) - expect(connection.requestRejection(loopback)).toBe(401) - expect(connection.requestRejection(declared)).toBe(401) - expect(connection.requestRejection(fakeRequest({ + expect(connection.admit(loopback)).toEqual({ rejection: 401 }) + expect(connection.admit(declared)).toEqual({ rejection: 401 }) + expect(connection.admit(fakeRequest({ host: 'harness.example', - cookie: browserCookie(connection, 'harness.example'), - }))).toBeUndefined() + cookie: await browserCookie(ctx, 'harness.example'), + }))).toHaveProperty('peer') await dispose() }) @@ -441,8 +528,8 @@ describe('connection node half', () => { const ctx = new Context() const routes: WebRoute[] = [] provideBrowserCredentials(ctx) - ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) - const fiber = ctx.plugin({ inject: [...inject], apply }) + ctx.provide('webServer', fakeHttpServer(ctx, routes, []) as WebServer) + const fiber = await mountConnection(ctx) await fiber.await() expect(routes).toHaveLength(2) expect(routes[0]).toMatchObject({ kind: 'prefix', path: API_PATH }) @@ -465,7 +552,7 @@ describe('connection node half', () => { const result = fakeResponse() await route!.handler(fakePost({ host: '127.0.0.1:3080', - cookie: browserCookie(connection, '127.0.0.1:3080'), + cookie: await browserCookie(ctx, '127.0.0.1:3080'), }, '/rpc/goals/create', request), result.response) expect(result.state.status).toBe(200) expect(JSON.parse(String(result.state.body))).toEqual({ @@ -490,8 +577,8 @@ describe('connection node half', () => { const ctx = new Context() const routes: WebRoute[] = [] provideBrowserCredentials(ctx) - ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) - const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) + ctx.provide('webServer', fakeHttpServer(ctx, routes, []) as WebServer) + const fiber = await mountConnection(ctx, { trustedHosts: ['harness.example'] }) await fiber.await() const connection = ctx.get('connection') as HostConnectionHandle const calls: unknown[] = [] @@ -522,7 +609,7 @@ describe('connection node half', () => { } const claimed = fakeResponse() - const loopbackCookie = browserCookie(connection, '127.0.0.1:3080') + const loopbackCookie = await browserCookie(ctx, '127.0.0.1:3080') await route.handler(fakePost({ host: '127.0.0.1:3080', cookie: loopbackCookie, }, '/api/goals/create', request), claimed.response) @@ -563,7 +650,7 @@ describe('connection node half', () => { const declared = fakeResponse() await route.handler(fakePost({ host: 'harness.example', - cookie: browserCookie(connection, 'harness.example'), + cookie: await browserCookie(ctx, 'harness.example'), }, '/api/goals/create', request), declared.response) expect(declared.state.status).toBe(200) await removeAuthenticated() @@ -571,7 +658,7 @@ describe('connection node half', () => { }) it('admits every trusted, authenticated request as the owner browser Peer and hands each call that Peer', async () => { - const { connection, routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) + const { ctx, connection, routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const peers: PeerScope[] = [] const remove = connection.rpc.intercept( '/api', @@ -583,8 +670,11 @@ describe('connection node half', () => { ) expect(connection.admit(fakeRequest({ host: 'other.example' }))).toEqual({ rejection: 403 }) expect(connection.admit(fakeRequest({ host: '127.0.0.1:3080' }))).toEqual({ rejection: 401 }) - const cookie = browserCookie(connection, '127.0.0.1:3080') - expect(connection.admit(fakeRequest({ host: '127.0.0.1:3080', cookie }))).toEqual({ peer: connection.browserPeer }) + const cookie = await browserCookie(ctx, '127.0.0.1:3080') + const admission = connection.admit(fakeRequest({ host: '127.0.0.1:3080', cookie })) + if ('rejection' in admission) throw new Error('valid token Cookie rejected') + const tokenPeer = admission.peer + expect(tokenPeer).not.toBe(connection.browserPeer) const route = routes.find(candidate => candidate.path === API_PATH)! const request: ClientRequest = { @@ -603,7 +693,7 @@ describe('connection node half', () => { body: JSON.stringify(request), }), connection.browserPeer) expect(direct.status).toBe(200) - expect(peers).toEqual([connection.browserPeer, connection.browserPeer]) + expect(peers).toEqual([tokenPeer, connection.browserPeer]) expect(connection.browserPeer.principal).toEqual({ kind: 'owner' }) // Racing disposals share one completion, and the scope goes with the Connection. @@ -616,8 +706,8 @@ describe('connection node half', () => { const ctx = new Context() const routes: WebRoute[] = [] provideBrowserCredentials(ctx) - ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) - const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) + ctx.provide('webServer', fakeHttpServer(ctx, routes, []) as WebServer) + const fiber = await mountConnection(ctx, { trustedHosts: ['harness.example'] }) await fiber.await() const connection = ctx.get('connection') as HostConnectionHandle const remove = connection.rpc.handle('/rpc', async (endpoint) => { @@ -627,7 +717,7 @@ describe('connection node half', () => { const route = routes.find(candidate => candidate.path === '/rpc')! const harnessHeaders = { host: 'harness.example', - cookie: browserCookie(connection, 'harness.example'), + cookie: await browserCookie(ctx, 'harness.example'), } const denied = fakeResponse() @@ -694,7 +784,7 @@ describe('operator-scoped connect', () => { query = '', headers: Record = {}, ): Promise<{ cookie: string; state: ReturnType['state'] }> { - const token = new URL(host.connection.authenticatedUrl('http://localhost')).search + const token = (await loginUrl(host.ctx, 'http://localhost')).search const response = fakeResponse() await host.routes.find(route => route.path === '/connect')!.handler( fakeRequest({ host: 'localhost', ...headers }, `/connect${token}${query}`), response.response, @@ -722,7 +812,7 @@ describe('operator-scoped connect', () => { expect(result.state).toMatchObject({ status, headers: { location, 'cache-control': 'no-store' } }) expect(admitted(host.connection, result.cookie).interactions).toBe(interactions) } - const rootCookie = browserCookie(host.connection, 'localhost') + const rootCookie = await browserCookie(host.ctx, 'localhost') expect(admitted(host.connection, rootCookie).interactions).toBe('answer') } finally { await host.dispose() } }) @@ -730,18 +820,16 @@ describe('operator-scoped connect', () => { it('keeps all browser cookies on the shared operator and creates independent API operators', async () => { const host = await mounted() try { - const cookie = browserCookie(host.connection, 'localhost') - expect(admitted(host.connection, cookie)).toBe(host.connection.browserPeer) - expect(admitted(host.connection, browserCookie(host.connection, 'localhost'))).toBe(host.connection.browserPeer) + const cookie = await browserCookie(host.ctx, 'localhost') + const browserPeer = admitted(host.connection, cookie) + expect(browserPeer).not.toBe(host.connection.browserPeer) + expect(admitted(host.connection, await browserCookie(host.ctx, 'localhost'))).toBe(browserPeer) const api = await connect(host, '', { cookie }) - expect(admitted(host.connection, api.cookie)).not.toBe(host.connection.browserPeer) + expect(admitted(host.connection, api.cookie)).not.toBe(browserPeer) const second = await connect(host, '', { cookie: api.cookie }) expect(admitted(host.connection, second.cookie)).not.toBe(admitted(host.connection, api.cookie)) - const denied = fakeResponse() - expect(host.connection.authorizeIndex(fakeRequest( - { host: 'localhost', cookie: api.cookie }, '/', - ), denied.response)).toBe(false) - expect(denied.state.status).toBe(401) + expect(host.ctx.connection.authentication.authenticate({ headers: { host: 'localhost', cookie: api.cookie } })) + .toEqual({ peer: admitted(host.connection, api.cookie) }) } finally { await host.dispose() } }) @@ -769,11 +857,25 @@ describe('operator-scoped connect', () => { } finally { await host.dispose() } }) + it('does not create an API credential for a cancelled connect request', async () => { + const host = await mounted() + try { + const cancellation = new AbortController() + cancellation.abort() + const request = fakeRequest({ host: 'localhost' }, (await loginUrl(host.ctx, 'http://localhost/connect')).href) + Object.assign(request, { signal: cancellation.signal }) + const response = fakeResponse() + await host.routes.find(route => route.path === '/connect')!.handler(request, response.response) + expect(response.state).toEqual({}) + expect(response.response.writableEnded).toBe(false) + } finally { await host.dispose() } + }) + it('refuses a captured connect request after the owning fiber is disposed', async () => { const host = await mounted() try { const route = host.routes.find(candidate => candidate.path === '/connect')! - const request = fakeRequest({ host: 'localhost' }, host.connection.authenticatedUrl('http://localhost/connect')) + const request = fakeRequest({ host: 'localhost' }, (await loginUrl(host.ctx, 'http://localhost/connect')).href) await host.dispose() const response = fakeResponse() @@ -812,18 +914,26 @@ describe('operator-scoped connect', () => { const pendingResponse = fakeResponse() const pending = api.handler(post('fixture/held'), pendingResponse.response) const signal = await started.promise - const owner = host.connection.admitConnection(fakeRequest({ host: 'localhost', cookie: first.cookie })) - if ('rejection' in owner) throw new Error('first socket was refused') - expect(owner.peer).toBe(peer) - expect(host.connection.admitConnection(fakeRequest({ host: 'localhost', cookie: first.cookie }))) - .toEqual({ rejection: 409 }) + const socket = new PassThrough() + const closed = once(socket, 'close') + const accepted = vi.fn(async () => {}) + await host.ctx.waterfall('webserver/upgrade', fakeRequest({ host: 'localhost', cookie: first.cookie }, '/api/remote.mux'), + socket, Buffer.alloc(0), peer, accepted) + expect(accepted).toHaveBeenCalledOnce() + const duplicate = new PassThrough() + const refused = vi.fn(async () => {}) + await host.ctx.waterfall('webserver/upgrade', fakeRequest({ host: 'localhost', cookie: first.cookie }, '/api/remote.mux'), + duplicate, Buffer.alloc(0), peer, refused) + expect(refused).not.toHaveBeenCalled() + expect(Buffer.concat(await duplicate.toArray()).toString()).toContain('409 Conflict') + duplicate.destroy() expect(admitted(host.connection, first.cookie)).toBe(peer) const cleanup = vi.fn() peer.ctx.effect(() => cleanup) - const released = owner.release() + socket.emit('error', new Error('connection closed')) expect(host.connection.admit(fakeRequest({ host: 'localhost', cookie: first.cookie }))).toEqual({ rejection: 401 }) - expect(owner.release()).toBe(released) - await released + await closed.catch(() => undefined) + await peer.dispose() expect(cleanup).toHaveBeenCalledOnce() expect(signal.aborted).toBe(false) finish.resolve(undefined) @@ -832,7 +942,7 @@ describe('operator-scoped connect', () => { const afterSocket = fakeResponse() await api.handler(post('fixture/now'), afterSocket.response) expect(afterSocket.state.status).toBe(401) - expect(host.connection.admitConnection(fakeRequest({ host: 'localhost', cookie: first.cookie }))) + expect(host.connection.admit(fakeRequest({ host: 'localhost', cookie: first.cookie }))) .toEqual({ rejection: 401 }) } finally { finish.resolve(undefined); await host.dispose() } }) @@ -857,21 +967,22 @@ describe('operator-scoped connect', () => { it('preserves browser tabs and restart recovery without resurrecting API operators', async () => { const host = await mounted() - const browser = { cookie: browserCookie(host.connection, 'localhost') } + const browser = { cookie: await browserCookie(host.ctx, 'localhost') } const api = await connect(host) const browserPeer = admitted(host.connection, browser.cookie) try { - const request = fakeRequest({ host: 'localhost', cookie: browser.cookie }) - const one = host.connection.admitConnection(request) - const two = host.connection.admitConnection(request) - if ('rejection' in one || 'rejection' in two) throw new Error('browser tab was refused') - expect(two.peer).toBe(one.peer) - await one.release() + const request = fakeRequest({ host: 'localhost', cookie: browser.cookie }, '/api/remote.mux') + const one = new PassThrough() + const two = new PassThrough() + const proceed = vi.fn(async () => {}) + await host.ctx.waterfall('webserver/upgrade', request, one, Buffer.alloc(0), browserPeer, proceed) + await host.ctx.waterfall('webserver/upgrade', request, two, Buffer.alloc(0), browserPeer, proceed) + expect(proceed).toHaveBeenCalledTimes(2) + one.destroy() + two.destroy() expect(admitted(host.connection, browser.cookie)).toBe(browserPeer) - await two.release() - expect(admitted(host.connection, browser.cookie)).toBe(browserPeer) - const refresh = fakeResponse() - expect(host.connection.authorizeIndex(fakeRequest({ host: 'localhost', cookie: browser.cookie }, '/'), refresh.response)).toBe(true) + expect(host.ctx.connection.authentication.authenticate({ headers: { host: 'localhost', cookie: browser.cookie } })) + .toEqual({ peer: browserPeer }) const cleanup = vi.fn() browserPeer.ctx.effect(() => cleanup) await host.dispose() @@ -879,7 +990,7 @@ describe('operator-scoped connect', () => { expect(host.connection.admit(request)).toEqual({ rejection: 401 }) const restarted = await mounted(undefined, 'http:', host.ctx.credentials) try { - expect(admitted(restarted.connection, browser.cookie)).toBe(restarted.connection.browserPeer) + expect(admitted(restarted.connection, browser.cookie)).not.toBe(restarted.connection.browserPeer) expect(admitted(restarted.connection, browser.cookie)).not.toBe(browserPeer) expect(restarted.connection.admit(fakeRequest({ host: 'localhost', cookie: api.cookie }))).toEqual({ rejection: 401 }) } finally { await restarted.dispose() } @@ -930,7 +1041,7 @@ describe('connection node half over a real HTTP server', () => { it('requires authentication uniformly over a real HTTP request', async () => { // A real IncomingMessage pins the exploit boundary: a client-controlled // Host naming loopback passes the rebinding fence but never authenticates. - const { routes, connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) + const { ctx, routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const { port, close } = await serve(routes) try { const methods = [ @@ -946,7 +1057,7 @@ describe('connection node half over a real HTTP server', () => { } expect(await call(port, 'settings/openSettingsDocument', 'other.example')).toBe(403) - const declaredCookie = browserCookie(connection, 'harness.example') + const declaredCookie = await browserCookie(ctx, 'harness.example') for (const method of methods) { expect([method, await call(port, method, 'harness.example', declaredCookie)]).toEqual([method, 404]) } @@ -955,7 +1066,7 @@ describe('connection node half over a real HTTP server', () => { port, 'settings/openSettingsDocument', loopbackAuthority, - browserCookie(connection, loopbackAuthority), + await browserCookie(ctx, loopbackAuthority), )).toBe(404) } finally { await close() diff --git a/packages/client/connection/tests/web-authorization.host.spec.ts b/packages/client/connection/tests/web-authorization.host.spec.ts new file mode 100644 index 0000000000..49f243da34 --- /dev/null +++ b/packages/client/connection/tests/web-authorization.host.spec.ts @@ -0,0 +1,76 @@ +/** WebServer admission applies Connection source checks once before route dispatch. */ +import { request as httpRequest } from 'node:http' +import { Context } from '@deepseek-ai/cordis' +import WebServer, { type WebRoute } from '@deepseek-ai/dsh-host-webserver' +import { afterEach, expect, it, vi } from 'vitest' +import * as Connection from '../src/index.ts' + +const roots: Context[] = [] +afterEach(async () => { for (const root of roots.splice(0)) await root.fiber.dispose() }) + +async function mounted() { + const ctx = new Context() + roots.push(ctx) + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }) + const connection = ctx.plugin(Connection) + await connection.await() + return { ctx, connection, origin: ctx.webServer.getOrigin() } +} + +it('checks anonymous route sources without authenticating their credentials', async () => { + const { ctx, origin } = await mounted() + const authenticate = vi.fn(() => ctx.connection.browserPeer) + ctx.connection.authentication.register({ authenticate }) + const handler = vi.fn((_request, response) => { response.end('public') }) + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/public', auth: 'anonymous', handler })) + for (const headers of [{ host: 'untrusted.example' }, { origin: 'http://untrusted.example' }, { 'sec-fetch-site': 'cross-site' }]) { + const status = await new Promise((resolve, reject) => { + const request = httpRequest(`${origin}/public`, { headers }, (response) => { + response.resume() + response.once('end', () => { resolve(response.statusCode) }) + }) + request.once('error', reject) + request.end() + }) + expect(status).toBe(403) + } + expect(handler).not.toHaveBeenCalled() + const response = await fetch(`${origin}/public`, { headers: { cookie: 'irrelevant=value' } }) + expect(response.status).toBe(200) + expect(await response.text()).toBe('public') + expect(authenticate).not.toHaveBeenCalled() + expect(handler.mock.calls[0]?.[2]).toBeUndefined() +}) + +it('authenticates once and passes the selected Peer to shared and custom RPC routes', async () => { + const { ctx, origin } = await mounted() + const peer = ctx.connection.createPeer({ principal: { kind: 'owner' } }) + const authenticate = vi.fn(() => peer) + ctx.connection.authentication.register({ authenticate }) + const handler = vi.fn(async (_endpoint, _payload, _signal, caller) => ({ ok: true, value: caller.id })) + ctx.connection.rpc.intercept('/api', () => true, handler) + await ctx.plugin({ inject: ['connection', 'webServer'], apply(owner: Context) { + owner.connection.rpc.handle('/custom', handler) + } }).await() + for (const channel of ['/api', '/custom']) { + const response = await fetch(`${origin}${channel}/fixture/read`, { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ type: 'client-request', rpcId: 'one', method: 'fixture/read', payload: {} }), + }) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ result: { ok: true, value: peer.id } }) + } + expect(authenticate).toHaveBeenCalledTimes(2) + expect(handler).toHaveBeenCalledTimes(2) + expect(handler.mock.calls.every(call => call[3] === peer)).toBe(true) +}) + +it('withdraws authorization with Connection and leaves authenticated routes unavailable', async () => { + const { ctx, connection, origin } = await mounted() + const handler = vi.fn((_request, response) => { response.end('private') }) + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/private', handler })) + expect((await fetch(`${origin}/private`)).status).toBe(401) + await connection.dispose() + expect((await fetch(`${origin}/private`)).status).toBe(503) + expect(handler).not.toHaveBeenCalled() +}) diff --git a/packages/client/connection/tsconfig.host.json b/packages/client/connection/tsconfig.host.json index 250b9eb34a..d5de678785 100644 --- a/packages/client/connection/tsconfig.host.json +++ b/packages/client/connection/tsconfig.host.json @@ -8,7 +8,7 @@ "files": [ "src/api-path.ts", "src/api-request-trust.ts", - "src/browser-auth.ts", + "src/authentication.ts", "src/client/random-uuid.ts", "src/client/rpc.ts", "src/connect-protocol.ts", diff --git a/packages/client/hmr/src/index.ts b/packages/client/hmr/src/index.ts index 23f5ca00d6..bfef8803a0 100644 --- a/packages/client/hmr/src/index.ts +++ b/packages/client/hmr/src/index.ts @@ -181,6 +181,7 @@ export function apply(ctx: Context, config: Config): void { const disposeRoute = ctx.webServer.register({ kind: 'exact', path: EVENTS_ENDPOINT, + auth: 'anonymous', handler: (req, res) => { // Named routes match ahead of the carrier's method gate; keep the old // global 405 semantics for non-GET hits on this endpoint. diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index 2bfda74d5f..52fa047650 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -702,7 +702,7 @@ export class ClientModuleRegistry extends Service { const registerWebCarrier = (webCtx: Context): void => { webCtx.effect( - () => webCtx.webServer.register({ kind: 'prefix', path: PLUGIN_ROUTE, resource: request => this.fetchBundle(request) }), + () => webCtx.webServer.register({ kind: 'prefix', path: PLUGIN_ROUTE, auth: 'anonymous', resource: request => this.fetchBundle(request) }), 'client-modules: bundle route', ) } diff --git a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts index 29ecb3a4a1..4e809d6289 100644 --- a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts @@ -5,8 +5,7 @@ import { join } from 'node:path' import { LocalFileSystem } from '@deepseek-ai/dsh-fs-local' import { WorkspaceFiles } from '@deepseek-ai/dsh-api-workspace-files' import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import type { SessionId } from '@deepseek-ai/dsh-session' import { SessionQueryError } from '@deepseek-ai/dsh-session-query' import type { SessionEventReadRequest } from '@deepseek-ai/dsh-session-query' @@ -72,7 +71,8 @@ async function fixture() { const opener = vi.fn(async (_request: { path: string; action?: 'reveal' }, _signal: AbortSignal) => ({ opened: true as const })) const applications = vi.fn(async () => [{ id: 'player', name: 'Player', default: true, icon: null }]) ctx.provide('sessionController', { workspacePathApplications: applications, openWorkspacePath: opener, workspaceDesktop: () => ({ name: 'desktop', available: true, fileManager: 'finder' }) } as never) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) await ctx.plugin(deliverables) const handler = connection.createSharedFetchHandler('/api') const open = (query = '?sessionId=owner&seq=9&index=0') => handler.fetch(new Request(`http://localhost${CHANGES_OPEN_PATH}${query}`, { method: 'POST' }), connection.browserPeer) diff --git a/packages/client/ui-deliverables/tests/present-open.host.spec.ts b/packages/client/ui-deliverables/tests/present-open.host.spec.ts index 688ec7af0a..e30c18936b 100644 --- a/packages/client/ui-deliverables/tests/present-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/present-open.host.spec.ts @@ -5,8 +5,7 @@ import { join } from 'node:path' import { LocalFileSystem } from '@deepseek-ai/dsh-fs-local' import { WorkspaceFiles } from '@deepseek-ai/dsh-api-workspace-files' import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import type { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' import { SessionQueryError } from '@deepseek-ai/dsh-session-query' @@ -57,7 +56,8 @@ async function fixture() { const opener = vi.fn(async (_request: { path: string; action?: 'reveal' }, _signal: AbortSignal) => ({ opened: true as const })) const applications = vi.fn(async () => [{ id: 'player', name: 'Player', default: true, icon: null }]) ctx.provide('sessionController', { workspacePathApplications: applications, resolveAgent, openWorkspacePath: opener, workspaceDesktop: () => ({ name: 'desktop', available: true, fileManager: 'finder' }) } as never) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: ['connection', 'sessionQuery', 'sessionController', 'workspaceFiles', 'fs', 'sandboxPolicy'], apply: registerPresentOpen }) await fiber const handler = connection.createSharedFetchHandler('/api') diff --git a/packages/credentials/deepseek-account/README.i18n.yaml b/packages/credentials/deepseek-account/README.i18n.yaml index 7c8e7b9d6f..c2be46689e 100644 --- a/packages/credentials/deepseek-account/README.i18n.yaml +++ b/packages/credentials/deepseek-account/README.i18n.yaml @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: a334962d65816a50 - zh: 28f66b089476123a + en: 1dcfc08cfb5df301 + zh: c43c462711e40d4a /deepseek-ai-dsh-deepseek-account/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/credentials/deepseek-account/README.md b/packages/credentials/deepseek-account/README.md index 28e3b20afe..307f8b424e 100644 --- a/packages/credentials/deepseek-account/README.md +++ b/packages/credentials/deepseek-account/README.md @@ -65,7 +65,7 @@ A private patch can read environment variables through Cordis expressions: process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} ``` -The authenticated client supplies its browser-accessible callback origin, including the local SSH forwarding port, and its UI kind. The service fixes the callback path and binds the resulting redirect_uri to both initialization and exchange. Callback requests use state and PKCE validation rather than RPC authentication. Completion, cancellation and disposal remove only the attempt route. Exchange failures publish failed state without retrying: Web closes its authorization tab and keeps the failure dialog in the original tab; the callback page attempts to close itself and offers a manual-close message. Desktop receives HTTP 204 and focuses its existing login UI through the account stream. +The authenticated client supplies its browser-accessible callback origin, including the local SSH forwarding port, and its UI kind. The service fixes the callback path and binds the resulting redirect_uri to both initialization and exchange. A temporary `webserver/request` listener handles this WebServer's exact callback authority and path before generic route admission, so valid cross-site browser returns reach state and PKCE validation rather than RPC authentication. Completion, cancellation and disposal remove only the attempt listener. Exchange failures publish failed state without retrying: Web closes its authorization tab and keeps the failure dialog in the original tab; the callback page attempts to close itself and offers a manual-close message. Desktop receives HTTP 204 and focuses its existing login UI through the account stream. Host diagnostics use `console.error` with the `[deepseek-account]` prefix on standard error and in the Host inspector Console, only for request, response-validation, or sign-in failures. Successful requests, caller cancellation, and normal account state changes are silent; request timeouts remain failures. Failure diagnostics include endpoint paths, HTTP status, numeric response codes, failure stages, invalid field paths, received types and validation codes, and browser URL rejection rules; headers, request and response bodies, authorization URLs, and raw exceptions are excluded. diff --git a/packages/credentials/deepseek-account/README.zh.md b/packages/credentials/deepseek-account/README.zh.md index 628fd2ed61..a7d92c0a79 100644 --- a/packages/credentials/deepseek-account/README.zh.md +++ b/packages/credentials/deepseek-account/README.zh.md @@ -65,7 +65,7 @@ platformOrigin 默认为 `https://platform.deepseek.com`,用于登录、资料 process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} ``` -已鉴权客户端提供浏览器可访问的回调来源(含 SSH 本地转发端口)和 UI 类型。服务固定回调路径,并在初始化与兑换时使用同一个 redirect_uri。回调请求使用 state 和 PKCE 校验,不要求 RPC 鉴权。完成、取消和卸载仅移除本次尝试的路由。兑换失败发布 failed 状态,不自动重试:Web 关闭授权标签页,原标签页显示失败弹窗;回调页尝试自行关闭,并提供手动关闭提示。Desktop 收到 HTTP 204,并通过账号状态流聚焦现有登录界面。 +已鉴权客户端提供浏览器可访问的回调来源(含 SSH 本地转发端口)和 UI 类型。服务固定回调路径,并在初始化与兑换时使用同一个 redirect_uri。临时 `webserver/request` 监听器在通用路由准入前处理本 WebServer 的精确回调 authority 和路径,让合法跨站浏览器返回进入 state 与 PKCE 校验,而非 RPC 鉴权。完成、取消和卸载仅移除本次尝试的监听器。兑换失败发布 failed 状态,不自动重试:Web 关闭授权标签页,原标签页显示失败弹窗;回调页尝试自行关闭,并提供手动关闭提示。Desktop 收到 HTTP 204,并通过账号状态流聚焦现有登录界面。 Host 诊断仅在请求、响应校验或登录失败时,通过 `console.error` 写入标准错误及 Host 调试器 Console,前缀为 `[deepseek-account]`。成功请求、调用方主动取消和正常账号状态变化不输出日志;请求超时仍记录为失败。失败诊断包含接口路径、HTTP 状态、数值响应码、失败阶段、校验失败的字段路径、实际类型和校验码,以及浏览器 URL 拒绝规则,不包含请求头、请求和响应正文、授权 URL 或原始异常。 diff --git a/packages/credentials/deepseek-account/package.json b/packages/credentials/deepseek-account/package.json index d97c62d027..581ff90497 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/credentials/deepseek-account/package.json @@ -66,6 +66,7 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/packages/credentials/deepseek-account/src/index.ts b/packages/credentials/deepseek-account/src/index.ts index 8dddec9074..f82de49dca 100644 --- a/packages/credentials/deepseek-account/src/index.ts +++ b/packages/credentials/deepseek-account/src/index.ts @@ -96,7 +96,7 @@ interface Attempt { running: Promise origin: string loginSource: 'web' | 'desktop' - disposeCallback?: () => Promise + disposeCallback?: () => boolean callback?: ServerResponse initialProfile?: { token: string; value: AccountDetails['profile'] } completionUrl?: string @@ -519,7 +519,7 @@ export class DeepSeekAccount extends TypertRemoteService { if (attempt.callback !== undefined) { await streamPromises.finished(attempt.callback, { cleanup: true }).catch(() => undefined) } - await attempt.disposeCallback?.() + attempt.disposeCallback?.() }) this.changed('snapshot') return this.getState() @@ -683,6 +683,7 @@ export class DeepSeekAccount extends TypertRemoteService { private async run(session: AuthorizationSession, attempt: Attempt): Promise { const webServer = this.ctx.get('webServer') if (webServer === undefined) throw new PlatformAuthError('protocol') + const callbackOrigin = new URL(attempt.origin) const verifier = randomBytes(32).toString('base64url') const state = randomBytes(32).toString('base64url') const challenge = createHash('sha256').update(verifier).digest('base64url') @@ -697,26 +698,29 @@ export class DeepSeekAccount extends TypertRemoteService { const abort = (): void => { code.reject(new PlatformAuthError('expired')) } signal.addEventListener('abort', abort, { once: true }) try { - attempt.disposeCallback = this.ctx.effect(() => webServer.register({ - kind: 'exact', path: '/oauth/callback', handler: (req, res) => { - let url: URL - try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } - catch { res.writeHead(400, { 'cache-control': 'no-store' }).end(); return } - const receivedCode = url.searchParams.get('code') - const receivedState = url.searchParams.get('state') ?? '' - const validState = Buffer.byteLength(receivedState) === Buffer.byteLength(state) - && timingSafeEqual(Buffer.from(receivedState), Buffer.from(state)) - if (req.method !== 'GET' || url.pathname !== '/oauth/callback' || !validState || !receivedCode - || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) { - res.writeHead(400, { 'cache-control': 'no-store' }).end(); return - } - if (signal.aborted || attempt.callback !== undefined || attempt.view.phase !== 'waiting-browser') { - res.writeHead(410, { 'cache-control': 'no-store' }).end(); return - } - attempt.callback = res - code.resolve(receivedCode) - }, - }), 'account: browser callback') + attempt.disposeCallback = this.ctx.on('webserver/request', async (req, res, next) => { + let receivedOrigin: URL + try { receivedOrigin = new URL(`http://${req.headers.host ?? ''}`) } + catch { await next(); return } + if (receivedOrigin.href !== callbackOrigin.href) { await next(); return } + let url: URL + try { url = new URL(req.url ?? '/', callbackOrigin) } + catch { res.writeHead(400, { 'cache-control': 'no-store' }).end(); return } + if (url.origin !== callbackOrigin.origin || url.pathname !== '/oauth/callback') { await next(); return } + const receivedCode = url.searchParams.get('code') + const receivedState = url.searchParams.get('state') ?? '' + const validState = Buffer.byteLength(receivedState) === Buffer.byteLength(state) + && timingSafeEqual(Buffer.from(receivedState), Buffer.from(state)) + if (req.method !== 'GET' || !validState || !receivedCode + || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) { + res.writeHead(400, { 'cache-control': 'no-store' }).end(); return + } + if (signal.aborted || attempt.callback !== undefined || attempt.view.phase !== 'waiting-browser') { + res.writeHead(410, { 'cache-control': 'no-store' }).end(); return + } + attempt.callback = res + code.resolve(receivedCode) + }) signal.throwIfAborted() const redirectUri = `${attempt.origin}/oauth/callback` const init = initialization.safeParse(await this.request('auth_init', { @@ -768,7 +772,7 @@ export class DeepSeekAccount extends TypertRemoteService { if (signal.aborted && authorizeId !== undefined) this.cancelRequest(authorizeId, verifier, attempt.clientHeaders) clearTimeout(timer) signal.removeEventListener('abort', abort) - // begin() settles the browser response and removes only this attempt’s route. + // begin() settles the browser response and removes only this attempt's callback listener. } } diff --git a/packages/credentials/deepseek-account/tests/account.spec.ts b/packages/credentials/deepseek-account/tests/account.spec.ts index 267616dab3..0ea495acf5 100644 --- a/packages/credentials/deepseek-account/tests/account.spec.ts +++ b/packages/credentials/deepseek-account/tests/account.spec.ts @@ -5,8 +5,9 @@ import { mkdtemp, rm, readFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { createServer as createTcpServer, connect, Socket } from 'node:net' import { join } from 'node:path' -import { createServer, IncomingMessage, ServerResponse } from 'node:http' +import { createServer, request as httpRequest, IncomingMessage, ServerResponse } from 'node:http' import WebServer from '@deepseek-ai/dsh-host-webserver' +import * as Connection from '@deepseek-ai/dsh-client-connection' import AuthorizationService from '@deepseek-ai/dsh-authorization' import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' @@ -194,6 +195,66 @@ async function fixture( init: () => init, count: () => count, callback: (state = init.state) => `${init.redirect_uri}?code=test&state=${state}` } } +it('accepts the cross-site OAuth return without relaxing other anonymous routes', async () => { + const f = await fixture() + const connection = f.ctx.plugin(Connection) + await connection.await() + cleanups.push(async () => { await connection.dispose() }) + const stop = f.ctx.webServer.register({ kind: 'exact', path: '/public', auth: 'anonymous', handler: (_req, res) => { res.end('public') } }) + cleanups.push(async () => { stop() }) + const headers = { 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'document' } + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'web') + await f.wait('waiting-browser') + expect((await fetch(`${f.callbackOrigin}/public`, { headers })).status).toBe(403) + expect((await fetch(f.callback('wrong'), { headers })).status).toBe(400) + expect(f.count()).toBe(0) + const response = await fetch(f.callback(), { headers, redirect: 'manual' }) + expect(response.status).toBe(302) + expect(response.headers.get('cache-control')).toBe('no-store') + expect(f.count()).toBe(1) + expect((await f.account.getState()).status).toBe('credential-stored') +}) + +it('leaves the attempt unconsumed on a different Host or HTTP listener', async () => { + const f = await fixture() + const connection = f.ctx.plugin(Connection) + await connection.await() + cleanups.push(async () => { await connection.dispose() }) + const isolated = f.ctx.isolate('webServer') + const other = isolated.plugin(WebServer, { host: '127.0.0.1', port: 0 }) + await other.await() + cleanups.push(async () => { await other.dispose() }) + const handled = vi.fn() + const remove = isolated.webServer.register({ kind: 'exact', path: '/oauth/callback', auth: 'anonymous', handler: (_req, res) => { + handled() + res.writeHead(204).end() + } }) + cleanups.push(async () => { remove() }) + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'web') + await f.wait('waiting-browser') + const callback = new URL(f.callback()) + const crossSite = { 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'document' } + const requestStatus = (url: URL, headers: Record): Promise => new Promise((resolve, reject) => { + const request = httpRequest(url, { headers }, (response) => { + response.on('error', reject) + response.once('end', () => { resolve(response.statusCode) }) + response.resume() + }) + request.on('error', reject) + request.end() + }) + expect(await requestStatus(callback, { ...crossSite, host: 'untrusted.invalid' })).toBe(404) + expect(await requestStatus(new URL(callback.pathname + callback.search, isolated.webServer.getOrigin()), { + host: callback.host, + })).toBe(204) + expect(handled).toHaveBeenCalledOnce() + expect(f.count()).toBe(0) + expect((await f.account.getState()).attempt?.phase).toBe('waiting-browser') + const accepted = await fetch(f.callback(), { headers: crossSite, redirect: 'manual' }) + expect(accepted.status).toBe(302) + expect(f.count()).toBe(1) +}) + it.each([ { serverTtl: 600, expectedRemaining: 480_000 }, { serverTtl: 60, expectedRemaining: 60_000 }, @@ -595,7 +656,7 @@ it('does not forward deployment cookies through a Platform redirect', async () = it('closes the failed Web authorization tab without redirecting and keeps the shared HTTP server alive', async () => { const f = await fixture() - const dispose = f.ctx.webServer.register({ kind: 'exact', path: '/health', handler: (_req, res) => { res.end('alive') } }) + const dispose = f.ctx.webServer.register({ kind: 'exact', path: '/health', auth: 'anonymous', handler: (_req, res) => { res.end('alive') } }) cleanups.push(async () => { dispose() }) await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'web') await f.wait('waiting-browser') @@ -1343,27 +1404,37 @@ it('rejects unsupported interaction and projects unexpected authorization failur } finally { begin.mockRestore() } }) -it('rejects callback requests whose raw URL is absent or malformed', async () => { +it('delegates other callback authorities and paths, and rejects malformed callback URLs', async () => { const f = await fixture() - const register = vi.spyOn(f.ctx.webServer, 'register') - try { - await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'web') - await f.wait('waiting-browser') - const route = register.mock.calls.find(([route]) => route.path === '/oauth/callback')?.[0] - if (route === undefined || !('handler' in route)) throw new Error('missing callback route') - for (const url of [undefined, 'http://[']) { - const socket = new Socket() - const req = new IncomingMessage(socket) - req.method = 'GET' - req.url = url - const res = new ServerResponse(req) - try { - await route.handler(req, res) + await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'web') + await f.wait('waiting-browser') + for (const input of [ + { url: f.callback(), host: undefined }, + { url: f.callback(), host: '[' }, + { url: 'http://untrusted.invalid/oauth/callback?code=test' }, + { url: undefined }, + { url: 'http://[' }, + ]) { + const socket = new Socket() + const req = new IncomingMessage(socket) + req.method = 'GET' + req.url = input.url + req.headers.host = 'host' in input ? input.host : new URL(f.callbackOrigin).host + const res = new ServerResponse(req) + const next = vi.fn(async () => {}) + try { + await f.ctx.waterfall(f.ctx.webServer, 'webserver/request', req, res, next) + if (input.url === 'http://[') { expect(res.statusCode).toBe(400) expect(res.writableEnded).toBe(true) - } finally { res.destroy(); socket.destroy() } - } - } finally { register.mockRestore() } + expect(next).not.toHaveBeenCalled() + } else { + expect(next).toHaveBeenCalledOnce() + expect(res.writableEnded).toBe(false) + } + expect(f.count()).toBe(0) + } finally { res.destroy(); socket.destroy() } + } }) it('settles an attempt after its browser callback connection closes during exchange', async () => { @@ -1371,22 +1442,19 @@ it('settles an attempt after its browser callback connection closes during excha f.hold() const response = Promise.withResolvers() const serverClosed = Promise.withResolvers() - const original = f.ctx.webServer.register.bind(f.ctx.webServer) - const register = vi.spyOn(f.ctx.webServer, 'register').mockImplementation(route => 'resource' in route ? original(route) : original({ - ...route, handler: (req, res) => { - response.resolve(res) - res.once('error', () => undefined) - res.once('close', () => { serverClosed.resolve(undefined) }) - return route.handler(req, res) - }, - })) + const remove = f.ctx.on('webserver/request', async (_req, res, next) => { + response.resolve(res) + res.once('error', () => undefined) + res.once('close', () => { serverClosed.resolve(undefined) }) + await next() + }) await f.account.startSignIn(clientMetadata(), f.callbackOrigin, 'web') await f.wait('waiting-browser') const socket = connect(Number(new URL(f.callbackOrigin).port), '127.0.0.1') const closed = new Promise(resolve => socket.once('close', () => { resolve() })) try { await new Promise(resolve => socket.once('connect', resolve)) - socket.write(`GET ${new URL(f.callback()).pathname}${new URL(f.callback()).search} HTTP/1.1\r\nHost: localhost\r\n\r\n`) + socket.write(`GET ${new URL(f.callback()).pathname}${new URL(f.callback()).search} HTTP/1.1\r\nHost: ${new URL(f.callbackOrigin).host}\r\n\r\n`) await f.exchanged.promise const callbackResponse = await response.promise vi.spyOn(callbackResponse, 'end').mockImplementation(() => callbackResponse) @@ -1397,7 +1465,7 @@ it('settles an attempt after its browser callback connection closes during excha f.release.resolve(undefined) await f.wait('succeeded') expect((await f.account.signOut(clientMetadata())).status).toBe('signed-out') - } finally { socket.destroy(); f.release.resolve(undefined); await closed; register.mockRestore() } + } finally { socket.destroy(); f.release.resolve(undefined); await closed; remove() } }) it('invalidates account reads before the shared grant lookup returns to its caller', async () => { diff --git a/packages/experimental/inspector/README.i18n.yaml b/packages/experimental/inspector/README.i18n.yaml index db0b17c1e6..36916d2cd5 100644 --- a/packages/experimental/inspector/README.i18n.yaml +++ b/packages/experimental/inspector/README.i18n.yaml @@ -15,8 +15,8 @@ en: 331f844c32631a82 zh: a9bc365f7d61d9ed /deepseek-ai-dsh-experimental-inspector/use-this-package: - en: 7d4d718b1a6f92ae - zh: 7ad283b159ae2c29 + en: 23c687afe1f73be0 + zh: 8e3642c9f16b827a /deepseek-ai-dsh-experimental-inspector/runtime-layout: en: 7db0c435e07d5005 zh: 1573972326c33893 diff --git a/packages/experimental/inspector/README.md b/packages/experimental/inspector/README.md index 2167e6d003..5dd4a209f9 100644 --- a/packages/experimental/inspector/README.md +++ b/packages/experimental/inspector/README.md @@ -37,7 +37,7 @@ The bundle sets `experimental-inspector` to `disabled: false` with `captureFetch When this component is enabled, **Ctrl/Cmd+Shift+.** toggles **NodeJS inspector** in the full-width bottom panel without requiring a selected Session. Drag its top edge to resize it, taking space from the content above; the selected height is retained across collapse and navigation. The focused divider also accepts Up/Down, Home and End. Its iframe loads on the first open and remains mounted while collapsed and across Session or main-panel navigation; unloading the component resets it. The X button and shortcut restore the opening control's focus when that control remains connected. The iframe automatically connects to this Host and opens Console; the manual Connection panel is omitted. Each embedded frontend shows Host and only its embedding page's Client in Console, Sources and the Cordis tree. The printed `devtools://` URL shows all Clients. -The Host serves the mirrored DevTools frontend at the application-relative `inspector/devtools/devtools_app.html` path, using the existing Web login. The `inspector/devtools` prefix redirects to that entry; GET and HEAD serve files, missing resources return 404, and other methods return 405. Its `cdp` WebSocket route authenticates the same browser session and forwards only to this Inspector's Worker page target. The bottom panel supplies its claimed `clientSourceId` to the entry and automatic WebSocket endpoint; the selection follows that logical Client across reconnects. An absent selector includes all Clients, an unavailable selected Client leaves Host visible, and empty or repeated selectors reject the upgrade with 400. Explicit `ws` or `wss` query parameters override the automatic endpoint, including its selection. +The Host serves the mirrored DevTools frontend at the application-relative `inspector/devtools/devtools_app.html` path, requiring WebServer admission and an owner Peer. The `inspector/devtools` prefix redirects to that entry; GET and HEAD serve files, missing resources return 404, and other methods return 405. Its `cdp` WebSocket route requires an owner Peer before opening the upstream connection and forwards only to this Inspector's Worker page target. The bottom panel supplies its claimed `clientSourceId` to the entry and automatic WebSocket endpoint; the selection follows that logical Client across reconnects. An absent selector includes all Clients, an unavailable selected Client leaves Host visible, and empty or repeated selectors reject the upgrade with 400. Explicit `ws` or `wss` query parameters override the automatic endpoint, including its selection. The build compiles the official `chrome-devtools-frontend@1.0.1638082` TypeScript sources with the root workspace's pinned [Vite dependency](../../../package.json). This npm snapshot is an ancestor of the Chromium 150 release branch, not an exact copy of its later stable release. The [source configuration](scripts/devtools/source.ts) and package manifest fix the version. Normal npm installation supplies the source and toolchain; building needs no appspot access, browser download, browser launch, or PAK extraction. Neither workspace installation nor published-package installation runs a DevTools download hook. diff --git a/packages/experimental/inspector/README.zh.md b/packages/experimental/inspector/README.zh.md index ed2f13ae08..56a8844361 100644 --- a/packages/experimental/inspector/README.zh.md +++ b/packages/experimental/inspector/README.zh.md @@ -37,7 +37,7 @@ kind: "package-reference" 启用此组件后,按 **Ctrl/Cmd+Shift+.** 可展开或收起整宽底部面板中的 **NodeJS 诊断**,无需选中 Session。拖动上边缘可调整面板高度,占用上方内容的可用空间;收起和切换页面时保留所选高度。聚焦分隔条后也可使用上/下方向键、Home 和 End。iframe 首次展开时加载,收起、切换 Session 或主面板时保持挂载;卸载此组件会重置前端。X 按钮和快捷键会在原打开控件仍连接时恢复其焦点。iframe 自动连接当前 Host 并打开 Console;不包含手动 Connection 面板。每个内嵌前端的 Console、Sources 和 Cordis 树只显示 Host 与嵌入它的页面所对应的 Client;打印的 `devtools://` 链接仍显示全部 Client。 -Host 在相对于应用根目录的 `inspector/devtools/devtools_app.html` 路径提供镜像后的 DevTools 前端,沿用现有 Web 登录鉴权。`inspector/devtools` 前缀重定向到该入口;GET 和 HEAD 提供文件,缺失资源返回 404,其他方法返回 405。其 `cdp` WebSocket 路由鉴权同一浏览器会话,只转发到当前 Inspector 的 Worker page target。底部面板将已声明的页面 `clientSourceId` 传给入口及自动 WebSocket 端点,重连时继续选择同一逻辑 Client。没有选择参数时包含全部 Client;指定 Client 不在线时保留 Host;空值或重复参数以 400 拒绝升级。显式 `ws` 或 `wss` query 参数覆盖自动端点及其选择范围。 +Host 在相对于应用根目录的 `inspector/devtools/devtools_app.html` 路径提供镜像后的 DevTools 前端,要求 WebServer 准入及 owner Peer。`inspector/devtools` 前缀重定向到该入口;GET 和 HEAD 提供文件,缺失资源返回 404,其他方法返回 405。其 `cdp` WebSocket 路由在打开上游连接前要求 owner Peer,只转发到当前 Inspector 的 Worker page target。底部面板将已声明的页面 `clientSourceId` 传给入口及自动 WebSocket 端点,重连时继续选择同一逻辑 Client。没有选择参数时包含全部 Client;指定 Client 不在线时保留 Host;空值或重复参数以 400 拒绝升级。显式 `ws` 或 `wss` query 参数覆盖自动端点及其选择范围。 构建使用官方 `chrome-devtools-frontend@1.0.1638082` TypeScript 源码及根 workspace 固定的 [Vite 依赖](../../../package.json)。该 npm 快照是 Chromium 150 发布分支的祖先,不是其后续稳定版的逐字节副本。[源码配置](scripts/devtools/source.ts)与包清单共同固定版本。普通 npm 安装提供源码和工具链;构建不需要 appspot、下载或启动浏览器,也不需要提取 PAK。workspace 安装和发布包安装都不运行 DevTools 下载 hook。 diff --git a/packages/experimental/inspector/src/host/plugin.ts b/packages/experimental/inspector/src/host/plugin.ts index b0eaf28c7f..7b4ac21d6a 100644 --- a/packages/experimental/inspector/src/host/plugin.ts +++ b/packages/experimental/inspector/src/host/plugin.ts @@ -92,13 +92,16 @@ export async function apply(ctx: Context, config: HostPluginConfig): Promise { res.setHeader('X-Content-Type-Options', 'nosniff') }, }) disposers.push(ctx.webServer.register({ - kind: 'prefix', path: DEVTOOLS_PATH, - handler: (req, res) => { + kind: 'prefix', path: DEVTOOLS_PATH, auth: 'required', + handler: (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + res.writeHead(403, { 'cache-control': 'no-store' }).end('forbidden') + return + } if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }).end() return } - if (!ctx.connection.authorizeIndex(req, res)) return const url = new URL(req.url ?? '/', 'http://inspector.invalid') if (url.pathname === DEVTOOLS_PATH || url.pathname === `${DEVTOOLS_PATH}/`) { const location = `${url.pathname === DEVTOOLS_PATH ? 'devtools/' : ''}devtools_app.html${url.search}` @@ -128,12 +131,10 @@ export async function apply(ctx: Context, config: HostPluginConfig): Promise { - const rejection = ctx.connection.requestRejection(req) - if (rejection !== undefined) { - const reason = rejection === 401 ? 'Unauthorized' : 'Forbidden' - socket.end(`HTTP/1.1 ${rejection} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`) + path: `${DEVTOOLS_PATH}/cdp`, auth: 'required', + handler: (req, socket, head, peer) => { + if (peer?.principal.kind !== 'owner') { + socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nCache-Control: no-store\r\nContent-Length: 0\r\n\r\n') return } const endpoint = new URL(target) diff --git a/packages/experimental/inspector/tests/bootstrap-route.host.spec.ts b/packages/experimental/inspector/tests/bootstrap-route.host.spec.ts index 2ecf5fe41e..7c29e36a8a 100644 --- a/packages/experimental/inspector/tests/bootstrap-route.host.spec.ts +++ b/packages/experimental/inspector/tests/bootstrap-route.host.spec.ts @@ -3,8 +3,7 @@ import { Context, FiberState } from '@deepseek-ai/cordis' import type { Message } from '@deepseek-ai/cordis' import type { IndexInjection, WebServer } from '@deepseek-ai/dsh-host-webserver' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import { setFlagsFromString } from 'node:v8' import { runInNewContext } from 'node:vm' import open from 'open' @@ -68,7 +67,8 @@ describe('experimental Inspector Host bootstrap route', () => { const registerUpgrade = vi.fn(() => () => {}) context.provide('webServer', { register, registerUpgrade } as Pick as WebServer) context.provide('cmdlineArgs', { get: () => args }) - const connection = new HostConnectionService(context, [], {} as BrowserAuth) + new ConnectionAuthentication(context) + const connection = new HostConnectionService(context, []) const api = connection.createSharedFetchHandler('/api') const messages: Message[] = [] context.logger.exporter({ levels: { default: 3 }, export: (message) => { messages.push(message) } }) diff --git a/packages/experimental/inspector/tests/fixtures/web-carrier.ts b/packages/experimental/inspector/tests/fixtures/web-carrier.ts new file mode 100644 index 0000000000..0eeac8e9c7 --- /dev/null +++ b/packages/experimental/inspector/tests/fixtures/web-carrier.ts @@ -0,0 +1,52 @@ +/** Synthetic WebServer dispatch for requests with partial Node response fixtures. */ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { Duplex } from 'node:stream' +import type { Context } from '@deepseek-ai/cordis' +import type { WebAdmission, WebAuthenticationRule, WebAuthRequest, WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' + +function authorize(ctx: Context, req: IncomingMessage, auth: WebAuthenticationRule | undefined, transport: WebAuthRequest['transport']): WebAdmission { + const request: WebAuthRequest = { + headers: req.headers, method: req.method, url: new URL(req.url ?? '/', 'http://127.0.0.1'), + transport, socket: req.socket, + } + const policy = typeof auth === 'function' ? auth(request) : auth ?? 'required' + if (policy === 'deny') return { kind: 'deny', status: 403 } + const admission: WebAdmission = ctx.bail('webserver/authorize', request, policy) + ?? (policy === 'anonymous' ? { kind: 'allow' } : { kind: 'deny', status: 503 }) + if (admission.kind === 'allow') { + if (policy === 'required' && admission.peer === undefined) return { kind: 'deny', status: 503 } + if (admission.peer?.signal.aborted) return { kind: 'deny', status: 401 } + } + return admission +} + +/** + * Dispatch an HTTP fixture through the registered authorization listener. + * @param ctx - Context owning the Connection authorization listener. + * @param route - Matched route registration. + * @param req - Incoming fixture request. + * @param res - Response recorder. + */ +export async function dispatchHttp(ctx: Context, route: WebRoute, req: IncomingMessage, res: ServerResponse): Promise { + const admission = authorize(ctx, req, route.auth, 'http') + if (admission.kind === 'deny') res.writeHead(admission.status).end() + else await route.handler(req, res, admission.peer) +} + +/** + * Dispatch an upgrade fixture through the registered authorization listener. + * @param ctx - Context owning the Connection authorization listener. + * @param route - Matched upgrade registration. + * @param req - Incoming fixture request. + * @param socket - Browser-side transport. + * @param head - Early upgrade bytes. + */ +export async function dispatchUpgrade( + ctx: Context, route: WebUpgradeRoute, req: IncomingMessage, socket: Duplex, head: Buffer, +): Promise { + const admission = authorize(ctx, req, route.auth, 'upgrade') + if (admission.kind === 'deny') { + const reason = { 401: 'Unauthorized', 403: 'Forbidden', 503: 'Service Unavailable' }[admission.status] + socket.end(`HTTP/1.1 ${String(admission.status)} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`) + } else await route.handler(req, socket, head, admission.peer) +} diff --git a/packages/experimental/inspector/tests/loader-composition.host.spec.ts b/packages/experimental/inspector/tests/loader-composition.host.spec.ts index f4972ba680..745d2f6093 100644 --- a/packages/experimental/inspector/tests/loader-composition.host.spec.ts +++ b/packages/experimental/inspector/tests/loader-composition.host.spec.ts @@ -1,6 +1,7 @@ /** Host Loader composition behavior. */ import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { request as httpRequest, type IncomingHttpHeaders } from 'node:http' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -8,9 +9,8 @@ import { Context } from '@deepseek-ai/cordis' import Include from '@deepseek-ai/cordis-plugin-include' import Loader from '@deepseek-ai/cordis-plugin-loader' import WebServer from '@deepseek-ai/dsh-host-webserver' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import { composeEntries, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' import open from 'open' import { afterEach, describe, expect, it, vi } from 'vitest' import * as Inspector from '../src/index.ts' @@ -29,6 +29,24 @@ afterEach(async () => { vi.clearAllMocks() }) +/** Collect an upgrade refusal after its response and socket have closed. */ +async function refusedUpgrade(url: string, origin: string): Promise<{ statusCode: number | undefined; headers: IncomingHttpHeaders }> { + return new Promise((resolve, reject) => { + const request = httpRequest(url, { agent: false, headers: { origin, connection: 'Upgrade', upgrade: 'websocket' } }) + request.once('response', (response) => { + response.once('error', reject) + response.resume() + request.once('close', () => { resolve({ statusCode: response.statusCode, headers: response.headers }) }) + }) + request.once('upgrade', (_response, socket) => { + socket.destroy() + reject(new Error('Inspector upgrade unexpectedly admitted')) + }) + request.once('error', reject) + request.end() + }) +} + describe('experimental Inspector through a real Loader composition', () => { it.each([false, true])('starts inspection with --inspect=%s and opens Chrome only when requested', async (flag) => { root = await mkdtemp(join(tmpdir(), 'dsh-inspector-loader-')) @@ -57,7 +75,7 @@ describe('experimental Inspector through a real Loader composition', () => { context.loader.builtins.include = Include const modules = new Map([ ['@deepseek-ai/dsh-host-webserver', WebServer], - ['fixture:connection', (ctx: Context) => { new HostConnectionService(ctx, [], {} as BrowserAuth) }], + ['fixture:connection', (ctx: Context) => { new ConnectionAuthentication(ctx); new HostConnectionService(ctx, []) }], ['@deepseek-ai/dsh-experimental-inspector', Inspector], ]) context.loader.internal = { @@ -92,6 +110,17 @@ describe('experimental Inspector through a real Loader composition', () => { const bootstrap = await api.fetch(new Request(`http://localhost${INSPECTOR_BOOTSTRAP_PATH}`), connection.browserPeer) expect(await bootstrap.json()).toHaveProperty('endpoint', expect.stringContaining('/ingest')) + const origin = context.webServer.getOrigin() + for (const [requestOrigin, status] of [[origin, 401], ['http://untrusted.invalid', 403]] as const) { + const page = await fetch(`${origin}/inspector/devtools/devtools_app.html`, { headers: { origin: requestOrigin } }) + expect(page.status).toBe(status) + expect(page.headers.get('cache-control')).toBe('no-store') + await page.text() + const upgraded = await refusedUpgrade(`${origin}/inspector/devtools/cdp`, requestOrigin) + expect(upgraded.statusCode).toBe(status) + expect(upgraded.headers['cache-control']).toBe('no-store') + } + await inspectorEntry!.fiber!.dispose() expect(context.get('inspector')).toBeUndefined() }) diff --git a/packages/experimental/inspector/tests/plugin-routes.host.spec.ts b/packages/experimental/inspector/tests/plugin-routes.host.spec.ts index 2eab724ce0..19e3815e62 100644 --- a/packages/experimental/inspector/tests/plugin-routes.host.spec.ts +++ b/packages/experimental/inspector/tests/plugin-routes.host.spec.ts @@ -2,15 +2,26 @@ import { randomBytes } from 'node:crypto' import type { IncomingMessage, ServerResponse } from 'node:http' -import { createConnection, createServer, type AddressInfo, type Socket } from 'node:net' +import { connect, createConnection, createServer, type AddressInfo, type Socket } from 'node:net' import { Context } from '@deepseek-ai/cordis' import type { Message } from '@deepseek-ai/cordis' import type { WebRoute, WebServer, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import * as Connection from '@deepseek-ai/dsh-client-connection' import { afterEach, describe, expect, it, vi } from 'vitest' import { apply, Config, inject, name } from '../src/index.ts' import { startInspector, type InspectorHandle } from '../src/host/bridge/controller.ts' +import { dispatchHttp, dispatchUpgrade } from './fixtures/web-carrier.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + inspectorAuthorizationTest: { readonly kind: 'inspector-authorization-test' } + } +} + +vi.mock('node:net', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, connect: vi.fn(actual.connect) } +}) type AssetMiddleware = (req: IncomingMessage, res: ServerResponse, next: (error?: unknown) => void) => void @@ -49,7 +60,7 @@ describe('experimental Inspector Host DevTools routes', () => { vi.clearAllMocks() }) - async function mount(options: { indexAllowed?: () => boolean; before?: (ctx: Context) => void } = {}) { + async function mount(options: { authenticated?: () => boolean; principal?: Connection.Principal; before?: (ctx: Context) => void } = {}) { context = new Context() vi.spyOn(console, 'log').mockImplementation(() => undefined) const routes: WebRoute[] = [] @@ -59,17 +70,12 @@ describe('experimental Inspector Host DevTools routes', () => { registerUpgrade: (route) => { upgrades.push(route); return () => {} }, } context.provide('webServer', webServer as WebServer) - const auth: Pick = { - isAuthenticated: () => true, - authenticateApi: () => undefined, - authorizeIndex: (_request, response) => { - if (options.indexAllowed?.() !== false) return true - response.writeHead(401) - response.end() - return false - }, - } - new HostConnectionService(context, [], auth as BrowserAuth) + await context.plugin(Connection).await() + const connection = context.connection + const peer = options.principal === undefined ? connection.browserPeer : connection.createPeer({ principal: options.principal }) + context.connection.authentication.register({ + authenticate: () => options.authenticated?.() !== false ? peer : undefined, + }) const messages: Message[] = [] context.logger.exporter({ levels: { default: 3 }, export: (message) => { messages.push(message) } }) options.before?.(context) @@ -77,13 +83,14 @@ describe('experimental Inspector Host DevTools routes', () => { return { fiber, routes, upgrades, messages } } - it('answers frontend requests by method, index authorization, redirect, and asset outcome', async () => { - let indexAllowed = true - const { fiber, routes, messages } = await mount({ indexAllowed: () => indexAllowed }) + it('answers frontend requests by authorization, method, redirect, and asset outcome', async () => { + let authenticated = true + const { fiber, routes, messages } = await mount({ authenticated: () => authenticated }) await fiber.await() const route = routes.find(row => row.path === '/inspector/devtools') if (route === undefined) throw new Error('DevTools route was not registered') - const call = async (method: string | undefined, url: string | undefined, headersSent = false) => { + const handler = vi.spyOn(route, 'handler') + const call = async (method: string | undefined, url: string | undefined, headersSent = false, origin = 'http://127.0.0.1') => { const recorded: RecordedResponse = { headers: {}, ended: false, destroyed: false } const res = { get headersSent() { return headersSent }, @@ -96,15 +103,19 @@ describe('experimental Inspector Host DevTools routes', () => { end() { recorded.ended = true; return this }, destroy() { recorded.destroyed = true; return this }, } - const req = { method, url, headers: {} } - await route.handler(req as IncomingMessage, res as ServerResponse) + const req = { method, url, headers: { host: '127.0.0.1', origin } } + await dispatchHttp(context!, route, req as IncomingMessage, res as ServerResponse) return { recorded, req } } expect((await call('POST', '/inspector/devtools/devtools_app.html')).recorded).toMatchObject({ status: 405, headers: { allow: 'GET, HEAD' }, ended: true }) - indexAllowed = false + handler.mockClear() + authenticated = false expect((await call('GET', '/inspector/devtools/devtools_app.html')).recorded.status).toBe(401) - indexAllowed = true + expect((await call('POST', '/inspector/devtools/devtools_app.html')).recorded.status).toBe(401) + authenticated = true + expect((await call('GET', '/inspector/devtools/devtools_app.html', false, 'http://untrusted.invalid')).recorded.status).toBe(403) + expect(handler).not.toHaveBeenCalled() expect(assets.middleware).not.toHaveBeenCalled() expect((await call('GET', '/inspector/devtools?panel=console')).recorded).toMatchObject({ status: 302, headers: { location: 'devtools/devtools_app.html?panel=console' }, @@ -117,6 +128,7 @@ describe('experimental Inspector Host DevTools routes', () => { }) const served = await call('GET', '/inspector/devtools/devtools_app.html?ws=1') expect(served.req.url).toBe('/devtools_app.html?ws=1') + expect(handler.mock.lastCall?.[2]).toBe(context!.connection.browserPeer) expect(served.recorded).toMatchObject({ status: 200, headers: { 'x-content-type-options': 'nosniff' } }) assets.middleware.mockImplementationOnce((_req, _res, next) => { next() }) @@ -135,6 +147,41 @@ describe('experimental Inspector Host DevTools routes', () => { .map((message): unknown => message.args[1])).toEqual([failure, failure]) }) + it('refuses an authenticated non-owner before serving assets or connecting CDP upstream', async () => { + const { fiber, routes, upgrades } = await mount({ principal: { kind: 'inspector-authorization-test' } }) + await fiber.await() + const route = routes.find(row => row.path === '/inspector/devtools') + const upgrade = upgrades.find(row => row.path === '/inspector/devtools/cdp') + if (route === undefined || upgrade === undefined) throw new Error('DevTools routes were not registered') + const writeHead = vi.fn().mockReturnThis() + const end = vi.fn().mockReturnThis() + const response: Pick = { writeHead, end } + const handler = vi.spyOn(route, 'handler') + await dispatchHttp(context!, route, { + method: 'GET', url: '/inspector/devtools/devtools_app.html', headers: { host: '127.0.0.1' }, + } as IncomingMessage, response as ServerResponse) + expect(handler.mock.lastCall?.[2]?.principal.kind).toBe('inspector-authorization-test') + expect(writeHead).toHaveBeenCalledWith(403, expect.objectContaining({ 'cache-control': 'no-store' })) + expect(end).toHaveBeenCalled() + expect(assets.middleware).not.toHaveBeenCalled() + + const pair = await socketPair() + const routeHandler = vi.spyOn(upgrade, 'handler') + vi.mocked(connect).mockClear() + try { + await dispatchUpgrade(context!, upgrade, upgradeRequest('/inspector/devtools/cdp', {}), pair.server, Buffer.alloc(0)) + expect(routeHandler.mock.lastCall?.[3]?.principal.kind).toBe('inspector-authorization-test') + expect(connect).not.toHaveBeenCalled() + await pair.closed + expect(pair.received().toString('latin1')).toContain('HTTP/1.1 403 Forbidden') + expect(pair.received().toString('latin1').toLowerCase()).toContain('cache-control: no-store') + } finally { + pair.server.destroy() + pair.client.destroy() + await pair.closed + } + }) + it('proxies authenticated CDP upgrades with their WebSocket headers and early bytes to the Worker', async () => { const { fiber, upgrades } = await mount() await fiber.await() @@ -143,7 +190,7 @@ describe('experimental Inspector Host DevTools routes', () => { const selected = await socketPair() const reply = readUpgrade(selected.client) - await upgrade.handler(upgradeRequest('/inspector/devtools/cdp?clientSourceId=client-fixture', { + await dispatchUpgrade(context!, upgrade, upgradeRequest('/inspector/devtools/cdp?clientSourceId=client-fixture', { 'sec-websocket-protocol': ['dsh-fixture', 'dsh-other'], 'sec-websocket-extensions': undefined, 'user-agent': 'fixture', @@ -156,13 +203,13 @@ describe('experimental Inspector Host DevTools routes', () => { const unselected = await socketPair() const later = readUpgrade(unselected.client) - await upgrade.handler(upgradeRequest(undefined, {}), unselected.server, Buffer.alloc(0)) + await dispatchUpgrade(context!, upgrade, upgradeRequest(undefined, {}), unselected.server, Buffer.alloc(0)) await vi.waitFor(() => { expect(unselected.received().toString('latin1')).toMatch(/^HTTP\/1\.1 101 /u) }) unselected.client.write(clientTextFrame(JSON.stringify({ id: 1, method: 'DSHInspector.getSources' }))) expect((await later).message).toMatchObject({ id: 1 }) const reset = await socketPair() - await upgrade.handler(upgradeRequest(undefined, {}), reset.server, Buffer.alloc(0)) + await dispatchUpgrade(context!, upgrade, upgradeRequest(undefined, {}), reset.server, Buffer.alloc(0)) reset.server.destroy(new Error('fixture browser reset')) await reset.closed @@ -183,7 +230,7 @@ describe('experimental Inspector Host DevTools routes', () => { const upgrade = upgrades.find(row => row.path === '/inspector/devtools/cdp') if (upgrade === undefined) throw new Error('CDP upgrade route was not registered') const pair = await socketPair() - await upgrade.handler(upgradeRequest(undefined, {}), pair.server, Buffer.alloc(0)) + await dispatchUpgrade(context!, upgrade, upgradeRequest(undefined, {}), pair.server, Buffer.alloc(0)) await pair.closed expect(pair.received().length).toBe(0) }) diff --git a/packages/experimental/inspector/tests/plugin.host.spec.ts b/packages/experimental/inspector/tests/plugin.host.spec.ts index 2496877a86..a688790057 100644 --- a/packages/experimental/inspector/tests/plugin.host.spec.ts +++ b/packages/experimental/inspector/tests/plugin.host.spec.ts @@ -3,17 +3,15 @@ import { PassThrough } from 'node:stream' import type { AddressInfo } from 'node:net' import { Context } from '@deepseek-ai/cordis' import type { IndexInjection, WebServer, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' +import * as Connection from '@deepseek-ai/dsh-client-connection' import open from 'open' import WebSocket, { type RawData } from 'ws' import { afterEach, describe, expect, it, vi } from 'vitest' import { apply, Config, inject, name, startInspector } from '../src/index.ts' import { isPlainObject } from '../src/shared/json.ts' import { INSPECTOR_BOOTSTRAP_PATH } from '../src/shared/web.ts' - -/** The Peer an index render speaks for; this listener reads no field of it. */ -const PAGE_PEER = { principal: { kind: 'owner' } } as Parameters[1] +import { dispatchUpgrade } from './fixtures/web-carrier.ts' vi.mock('open', () => ({ default: vi.fn(async () => undefined), apps: { chrome: 'chrome' } })) @@ -41,12 +39,11 @@ describe('experimental Inspector Host plugin', () => { const registerUpgrade = vi.fn<(_route: WebUpgradeRoute) => () => void>(() => releaseUpgrade) const routes: Pick = { register: registerRoute, registerUpgrade } let authenticated = false - const auth: Pick = { - isAuthenticated: () => authenticated, - authenticateApi: () => undefined, - } context.provide('webServer', routes as WebServer) - const connection = new HostConnectionService(context, [], auth as BrowserAuth) + await context.plugin(Connection).await() + const connection = context.connection + registerRoute.mockClear() + context.connection.authentication.register({ authenticate: () => authenticated ? connection.browserPeer : undefined }) const fiber = context.plugin( { name, inject: [...inject], Config, apply }, { port: 0, captureFetch: false }, @@ -54,7 +51,7 @@ describe('experimental Inspector Host plugin', () => { await fiber.await() const rows: IndexInjection[] = [] - context.emit('webserver/index-inject', rows, PAGE_PEER) + context.emit('webserver/index-inject', rows, connection.browserPeer) const bootstrap = rows.find(row => row.kind === 'global' && row.name === '__DSH_INSPECTOR__') expect(bootstrap).toMatchObject({ kind: 'global', name: '__DSH_INSPECTOR__' }) expect(log).toHaveBeenCalledWith(expect.stringMatching(/^dsh inspector: devtools:\/\//u)) @@ -64,14 +61,14 @@ describe('experimental Inspector Host plugin', () => { const upgrade = registerUpgrade.mock.calls[0]![0] for (const [origin, status] of [['http://127.0.0.1', 401], ['http://untrusted.invalid', 403]] as const) { const socket = new PassThrough() - await upgrade.handler({ headers: { host: '127.0.0.1', origin } } as IncomingMessage, socket, Buffer.alloc(0)) + await dispatchUpgrade(context, upgrade, { headers: { host: '127.0.0.1', origin } } as IncomingMessage, socket, Buffer.alloc(0)) expect(String(socket.read())).toContain(`HTTP/1.1 ${status}`) socket.destroy() } authenticated = true for (const query of ['clientSourceId=', 'clientSourceId=a&clientSourceId=b']) { const socket = new PassThrough() - await upgrade.handler({ url: `/inspector/devtools/cdp?${query}`, headers: { host: '127.0.0.1', origin: 'http://127.0.0.1' } } as IncomingMessage, socket, Buffer.alloc(0)) + await dispatchUpgrade(context, upgrade, { url: `/inspector/devtools/cdp?${query}`, headers: { host: '127.0.0.1', origin: 'http://127.0.0.1' } } as IncomingMessage, socket, Buffer.alloc(0)) expect(String(socket.read())).toContain('HTTP/1.1 400') socket.destroy() } @@ -117,10 +114,10 @@ describe('experimental Inspector Host plugin', () => { await fiber.dispose() expect(releaseRoute).toHaveBeenCalledOnce() expect(releaseUpgrade).toHaveBeenCalledOnce() - expect(rows).toHaveLength(1) + expect(rows.filter(row => row.kind === 'global' && row.name === '__DSH_INSPECTOR__')).toHaveLength(1) const afterDispose: IndexInjection[] = [] - context.emit('webserver/index-inject', afterDispose, PAGE_PEER) - expect(afterDispose).toEqual([]) + context.emit('webserver/index-inject', afterDispose, connection.browserPeer) + expect(afterDispose.some(row => row.kind === 'global' && row.name === '__DSH_INSPECTOR__')).toBe(false) expect((await api.fetch(new Request(`http://localhost${INSPECTOR_BOOTSTRAP_PATH}`), connection.browserPeer)).status).toBe(404) }) @@ -129,7 +126,8 @@ describe('experimental Inspector Host plugin', () => { context = new Context() const routes: Pick = { register: () => () => {}, registerUpgrade: () => () => {} } context.provide('webServer', routes as WebServer) - new HostConnectionService(context, [], {} as BrowserAuth) + new ConnectionAuthentication(context) + new HostConnectionService(context, []) context.provide('inspector', { publish: () => undefined, cordis: { getTree: () => Promise.reject(new Error('unused test service')) }, @@ -151,7 +149,8 @@ describe('experimental Inspector Host plugin', () => { const routes: Pick = { register: () => () => {}, registerUpgrade: () => () => {} } context.provide('webServer', routes as WebServer) context.provide('cmdlineArgs', { get: () => ['--inspect'] }) - const connection = new HostConnectionService(context, [], {} as BrowserAuth) + new ConnectionAuthentication(context) + const connection = new HostConnectionService(context, []) vi.mocked(open).mockRejectedValueOnce(new Error('Chrome unavailable')) const fiber = context.plugin({ name, inject: [...inject], Config, apply }, { port: 0, captureFetch: false }) await fiber.await() diff --git a/packages/experimental/liveshare/tests/viewer-cancel-admission.spec.ts b/packages/experimental/liveshare/tests/viewer-cancel-admission.spec.ts index ca2f76b64f..2faf173930 100644 --- a/packages/experimental/liveshare/tests/viewer-cancel-admission.spec.ts +++ b/packages/experimental/liveshare/tests/viewer-cancel-admission.spec.ts @@ -24,9 +24,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { ConnectionAuthentication } from '@deepseek-ai/dsh-client-connection' import { HostConnectionService } from '../../../client/connection/src/rpc-host.ts' -import { BrowserAuth } from '../../../client/connection/src/browser-auth.ts' -import { provideBrowserCredentials } from '../../../api/gateway/tests/browser-credentials.ts' import { createSessionTestController } from '../../../api/session-controller/tests/test-remote.ts' import { SessionController, type SessionCancelRequest } from '../../../api/session-controller/src/index.ts' import type { TypertLookup } from '../../../typert/protocol/src/types.ts' @@ -86,9 +85,8 @@ async function readerHarness(creator: ShareRpcActor, target: 'fork' | 'source' = await ctx.plugin(TypertRegistry) await mountAgentLoopTestDependencies(ctx) const driver = await mountAgentLoopTestHarness(ctx) - provideBrowserCredentials(ctx) - const auth = await BrowserAuth.create(ctx, ctx.credentials, 1) - new HostConnectionService(ctx, [], auth) + new ConnectionAuthentication(ctx) + new HostConnectionService(ctx, []) // Provided on the root Context that also constructs the Session controller below, which re-reads // access from that Context's own fiber while a Gateway call runs. new RemoteAccessService(ctx) diff --git a/packages/experimental/liveshare/tests/viewer-target-admission.spec.ts b/packages/experimental/liveshare/tests/viewer-target-admission.spec.ts index d9dd45eb77..d771035e78 100644 --- a/packages/experimental/liveshare/tests/viewer-target-admission.spec.ts +++ b/packages/experimental/liveshare/tests/viewer-target-admission.spec.ts @@ -19,9 +19,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { ConnectionAuthentication } from '@deepseek-ai/dsh-client-connection' import { HostConnectionService } from '../../../client/connection/src/rpc-host.ts' -import { BrowserAuth } from '../../../client/connection/src/browser-auth.ts' -import { provideBrowserCredentials } from '../../../api/gateway/tests/browser-credentials.ts' import { createSessionTestController } from '../../../api/session-controller/tests/test-remote.ts' import { ForkRegistry } from '../src/host/fork-registry.ts' import { READ_ONLY_FORK_CEILING, type ForkShareState, type ViewerSessionMode } from '../src/host/fork-policy.ts' @@ -55,9 +54,8 @@ async function harness(mode: ViewerSessionMode = 'write') { await ctx.plugin(TypertRegistry) await mountAgentLoopTestDependencies(ctx) const driver = await mountAgentLoopTestHarness(ctx) - provideBrowserCredentials(ctx) - const auth = await BrowserAuth.create(ctx, ctx.credentials, 1) - new HostConnectionService(ctx, [], auth) + new ConnectionAuthentication(ctx) + new HostConnectionService(ctx, []) // Provided on the root Context that also constructs the Session controller below, which re-reads // access from that Context's own fiber while a Gateway call runs. new RemoteAccessService(ctx) diff --git a/packages/experimental/webhook-github/src/index.ts b/packages/experimental/webhook-github/src/index.ts index fd11ce4af3..bcb6bfbc60 100644 --- a/packages/experimental/webhook-github/src/index.ts +++ b/packages/experimental/webhook-github/src/index.ts @@ -48,6 +48,7 @@ export function apply(ctx: Context, config: Config): void { assertConfig(config) const route = { kind: 'exact' as const, + auth: 'anonymous' as const, path: config.path, handler: createGitHubWebhookHandler(ctx, { source: config.source, diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index d353570e40..18425b7064 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -760,7 +760,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'readonly browserPeer: PeerScope', - description: 'The owner Peer every authenticated browser connection shares.', + description: 'Connection-owned Peer for trusted in-process callers, not network authentication.', parameters: [], }, { @@ -774,41 +774,41 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'channel', description: 'shared channel mounted by Connection.' }], returns: 'Fetch handler for trusted, authenticated requests.', }, - { - signature: 'requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection', - description: 'Apply Connection\'s Host/Origin checks and browser authentication to another Web route.', - parameters: [{ name: 'request', description: 'request headers from the HTTP or upgrade request.' }], - returns: 'rejection status, or undefined when the route may accept the request.', - }, { signature: 'admit(request: ConnectionTrustRequest): PeerAdmission', - description: 'Admit an HTTP request against its signed browser or API credential and live Peer.', + description: 'Apply Host/Origin checks and admit the first live Peer returned by a registered credential verifier.', parameters: [{ name: 'request', description: 'request headers from the HTTP or upgrade request.' }], returns: 'the credential\'s Peer, or the rejection status.', }, { signature: 'createPeer(options: { readonly principal: Principal; readonly interactions?: \'answer\' | \'none\' }): PeerScope', description: 'Create an independent in-process Peer, disposed with the Context that read `ctx.connection`.', - parameters: [{ name: 'options', description: 'fixed principal and optional interaction participation (default `answer`).' }], + parameters: [{ name: 'options', description: 'fixed principal and interaction participation (default answer).' }], returns: 'a new Peer distinct from every other Peer.', }, { - signature: 'admitConnection(request: ConnectionTrustRequest): ConnectionAdmission', - description: 'Claim a physical socket for an API Peer; browser sockets share their owner Peer.', - parameters: [{ name: 'request', description: 'authenticated upgrade request headers.' }], - returns: 'the Peer and idempotent release, or 409 for duplicate API ownership. The carrier releases on socket termination or failed upgrade; release removes API admission synchronously without cancelling independent HTTP calls.', + signature: 'readonly authentication: ConnectionAuthentication', + description: 'Credential verifier sub-service; consumers inject `connection.authentication`.', + parameters: [], + }, + ], + }, + { + key: 'connection.authentication', + summary: 'Credential verifier registry whose registrations belong to the calling plugin.', + description: 'Credential verifier registry whose registrations belong to the calling plugin.', + methods: [ + { + signature: 'register(provider: AuthenticationProvider): () => Promise', + description: 'Add a credential verifier after the existing registrations.', + parameters: [{ name: 'provider', description: 'verifier owning its credential and Peer selection.' }], + returns: 'disposer withdrawing this registration; the calling scope also withdraws it on unload.', }, { - signature: 'authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean', - description: 'Authenticate one frontend index request, owning a token redirect or 401. The cookie this mints is `Secure` when the mounted Web carrier serves TLS, which only that listener\'s protocol decides.', - parameters: [{ name: 'request', description: 'root or configured-index HTTP request.' }, { name: 'response', description: 'response owned when the result is false.' }], - returns: 'true only when the frontend may serve index.html.', - }, - { - signature: 'authenticatedUrl(baseUrl: string): string', - description: 'Add the fresh process token to an ordinary Web application URL.', - parameters: [{ name: 'baseUrl', description: 'clean application URL whose authority and mount are preserved.' }], - returns: 'tokenized URL for initial login; a mount proxy strips its prefix before {@link authorizeIndex}.', + signature: 'authenticate(request: ConnectionTrustRequest): PeerAdmission', + description: 'Verify credentials without applying an HTTP response or source policy.', + parameters: [{ name: 'request', description: 'current carrier headers and cancellation facts.' }], + returns: 'the first live Peer, 401 if no provider accepts, or 503 when verification failed without success.', }, ], }, @@ -4694,7 +4694,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'webServer', summary: 'The browser HTTP carrier service.', - description: 'The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and a request no named route matches is answered 404 until the fallback owner registers.', + description: 'The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and a request no named route matches is answered 404 until the fallback owner registers. HTTP and upgrade admission refusals carry `Cache-Control: no-store`.', methods: [ { signature: 'getOrigin(): string', @@ -4716,14 +4716,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the disposer removing the route.', }, { - signature: 'registerFallback(fallback: WebRoute[\'handler\'] | Pick): () => void', + signature: 'registerFallback(fallback: WebRoute[\'handler\'] | WebFallback): () => void', description: 'Claim the fallback seat: the handler or resource answering every request no named route matches (the SPA dist server in the shipped Web composition). One owner only — a second registration throws, because two fallbacks cannot compose.', - parameters: [{ name: 'fallback', description: 'a handler owning the full response lifecycle of unmatched requests, or `{ resource }` answering them.' }], + parameters: [{ name: 'fallback', description: 'a handler owning the full response lifecycle of unmatched requests, or an object declaring `handler` or `resource` and auth.' }], returns: 'the disposer releasing the seat.', }, { signature: 'async readResource(request: Request, peer: PeerScope): Promise', - description: 'Read the response an HTTP request for the same URL would receive, as the resource computes it for `peer`, without an HTTP exchange. The request path picks the responder by the HTTP match order — exact, longest prefix, then the fallback — and only a resource answers. This method checks no cookie, Host, or Origin: the caller admits the reader before reading.', + description: 'Read the response an HTTP request for the same URL would receive, as the resource computes it for `peer`, without an HTTP exchange. The request path picks the responder by the HTTP match order — exact, longest prefix, then the fallback — and only a resource answers. This method checks no cookie, Host, or Origin: the caller admits the reader before reading. A resolved deny policy returns 403 even for an explicitly admitted Peer.', parameters: [{ name: 'request', description: 'the read; its URL path selects the responder.' }, { name: 'peer', description: 'the Peer the read speaks for, passed to the resource.' }], returns: 'the resource\'s response, without a body for HEAD as over HTTP; 405 with `Allow: GET, HEAD` for any other method, checked before matching, where over HTTP a handler route or an unmatched path answers such a method itself; 404 when the path matches a handler route, or reaches the fallback seat while it is unclaimed or holds a handler. A resource that throws rejects the read, where an HTTP request would receive 400.', }, @@ -5696,6 +5696,22 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'The set of registered search or fetch providers changed: one provider registered, or its registration was disposed. Payload-free; consumers re-read `ctx.web.listProviders()` (Remote `web/listProviders`) for the new list. Fires after each committed registry mutation. Observer failures are contained and cannot veto the mutation.', parameters: [], }, + { + name: 'webserver/authorize', + mode: 'bail', + signature: '\'webserver/authorize\'(request: WebAuthRequest, policy: WebAuthPolicy): WebAdmission | undefined', + summary: 'Admit a matched request synchronously; the first decision wins.', + description: 'Admit a matched request synchronously; the first decision wins.', + parameters: [{ name: 'request', description: 'headers, target, transport, and available cancellation state.' }, { name: 'policy', description: 'resolved route policy; deny never emits this event.' }], + }, + { + name: 'webserver/entry-url', + mode: 'emit', + signature: '\'webserver/entry-url\'(baseUrl: string, entries: WebEntryUrl[]): void', + summary: 'Collect complete entry URLs for an advertised server address.', + description: 'Collect complete entry URLs for an advertised server address.', + parameters: [{ name: 'baseUrl', description: 'advertised server base URL without provider credentials.' }, { name: 'entries', description: 'entries appended synchronously in listener order.' }], + }, { name: 'webserver/index-inject', mode: 'emit', @@ -5704,6 +5720,22 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Collect the structured index injection table for the page `peer` speaks for. Emitted on every index render and every worker boot-payload request; listeners push their current rows, so a row\'s data is read fresh at emit time.', parameters: [{ name: 'table', description: 'Mutable row table; listeners append in activation order.' }, { name: 'peer', description: 'The Peer the rendered page speaks for.' }], }, + { + name: 'webserver/request', + mode: 'waterfall', + signature: '\'webserver/request\'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise', + summary: 'Handle an HTTP request before named-route and fallback dispatch.', + description: 'Handle an HTTP request before named-route and fallback dispatch.', + parameters: [{ name: 'request', description: 'original incoming HTTP request.' }, { name: 'response', description: 'response owned by the listener or its delegated handler.' }, { name: 'next', description: 'dispatch to the next listener or the matching route.' }], + }, + { + name: 'webserver/upgrade', + mode: 'waterfall', + signature: '\'webserver/upgrade\'( request: IncomingMessage, socket: Duplex, head: Buffer, peer: PeerScope | undefined, next: () => Promise, ): Promise', + summary: 'Handle an admitted upgrade before its registered protocol handler.', + description: 'Handle an admitted upgrade before its registered protocol handler.', + parameters: [{ name: 'request', description: 'original upgrade request.' }, { name: 'socket', description: 'transport owned by the upgrade.' }, { name: 'head', description: 'bytes received after the HTTP headers.' }, { name: 'peer', description: 'authenticated identity, absent for anonymous admission.' }, { name: 'next', description: 'delegate to the next listener or protocol handler.' }], + }, { name: 'workflow/agent-end', mode: 'emit', @@ -6104,6 +6136,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AttachmentId', declaration: 'export type AttachmentId = Branded<\'AttachmentId\'>;', }, + { + name: 'AuthenticationProvider', + declaration: 'export interface AuthenticationProvider {\n authenticate(request: ConnectionTrustRequest): PeerScope | undefined;\n}', + }, { name: 'AuthorizationEntry', declaration: 'export interface AuthorizationEntry {\n key: CredentialKey;\n label: string;\n methods: readonly AuthorizationMethod[];\n inFlight: boolean;\n}', @@ -6365,8 +6401,8 @@ export const TYPE_API: readonly TypeApiEntry[] = [ declaration: 'export type ConfinedSandboxMode = Exclude;', }, { - name: 'ConnectionAdmission', - declaration: 'export type ConnectionAdmission = {\n readonly peer: PeerScope;\n readonly release: () => Promise;\n} | {\n readonly rejection: 401 | 403 | 409;\n};', + name: 'ConnectionAuthentication', + declaration: 'export class ConnectionAuthentication extends Service {\n constructor(ctx: Context);\n register(provider: AuthenticationProvider): () => Promise;\n authenticate(request: ConnectionTrustRequest): PeerAdmission;\n}', }, { name: 'ConnectionFetchHandler', @@ -6380,22 +6416,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ConnectionFetchRoute', declaration: 'export interface ConnectionFetchRoute {\n readonly path: string;\n readonly methods: readonly ConnectionFetchMethod[];\n readonly requestBody: ConnectionRequestBodyMode;\n readonly fetch: (request: Request) => Promise;\n}', }, - { - name: 'ConnectionIndexRequest', - declaration: 'export interface ConnectionIndexRequest extends ConnectionTrustRequest {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n}', - }, - { - name: 'ConnectionIndexResponse', - declaration: 'export interface ConnectionIndexResponse {\n writeHead(status: number, headers?: Readonly>): unknown;\n end(body?: string): unknown;\n}', - }, { name: 'ConnectionRequestBodyMode', declaration: 'export type ConnectionRequestBodyMode = \'buffered\' | \'streaming\';', }, - { - name: 'ConnectionRequestRejection', - declaration: 'export type ConnectionRequestRejection = 401 | 403 | undefined;', - }, { name: 'ConnectionRpcAttachment', declaration: 'export interface ConnectionRpcAttachment {\n readonly path: readonly (string | number)[];\n readonly bytes: Uint8Array;\n}', @@ -6422,7 +6446,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ConnectionTrustRequest', - declaration: 'export interface ConnectionTrustRequest {\n readonly headers: Headers | Readonly>;\n}', + declaration: 'export interface ConnectionTrustRequest {\n readonly headers: Headers | Readonly>;\n readonly signal?: AbortSignal | undefined;\n readonly socket?: {\n readonly destroyed: boolean;\n } | undefined;\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n}', }, { name: 'ContentBlockMap', @@ -8114,7 +8138,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'PeerAdmission', - declaration: 'export type PeerAdmission = {\n readonly peer: PeerScope;\n} | {\n readonly rejection: 401 | 403;\n};', + declaration: 'export type PeerAdmission = {\n readonly peer: PeerScope;\n} | {\n readonly rejection: 401 | 403 | 503;\n};', }, { name: 'PeerId', @@ -10636,6 +10660,22 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ViewerPluginPolicy', declaration: 'export interface ViewerPluginPolicy {\n readonly plugin: string;\n readonly mode: \'all\' | \'none\' | \'selected\';\n readonly endpoints?: readonly string[];\n}', }, + { + name: 'WebAdmission', + declaration: 'export type WebAdmission = {\n kind: \'allow\';\n peer?: PeerScope;\n} | {\n kind: \'deny\';\n status: 401 | 403 | 503;\n};', + }, + { + name: 'WebAuthenticationRule', + declaration: 'export type WebAuthenticationRule = WebAuthPolicy | ((request: WebAuthRequest) => WebAuthPolicy);', + }, + { + name: 'WebAuthPolicy', + declaration: 'export type WebAuthPolicy = \'anonymous\' | \'required\' | \'deny\';', + }, + { + name: 'WebAuthRequest', + declaration: 'export interface WebAuthRequest {\n headers: Headers | Readonly>;\n method?: string | undefined;\n url: URL;\n transport: \'http\' | \'upgrade\';\n signal?: AbortSignal | undefined;\n socket?: {\n readonly destroyed: boolean;\n } | undefined;\n}', + }, { name: 'WebBootBatch', declaration: 'export interface WebBootBatch {\n phase: WebBootBatchPhase;\n url: string;\n rev: string;\n entries: string[];\n}', @@ -10656,6 +10696,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WebBootRelease', declaration: 'export interface WebBootRelease {\n version: string;\n commit?: string;\n}', }, + { + name: 'WebEntryUrl', + declaration: 'export interface WebEntryUrl {\n readonly label: string;\n readonly url: string;\n readonly open: boolean;\n}', + }, + { + name: 'WebFallback', + declaration: 'export type WebFallback = Pick | Pick;', + }, { name: 'WebFetchBody', declaration: 'export type WebFetchBody = {\n readonly kind: \'html\';\n readonly content: string;\n} | {\n readonly kind: \'text\';\n readonly content: string;\n};', @@ -10722,7 +10770,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'WebResourceRoute', - declaration: 'export interface WebResourceRoute {\n kind: WebRouteKind;\n path: string;\n resource: WebResource;\n}', + declaration: 'export interface WebResourceRoute {\n kind: WebRouteKind;\n path: string;\n resource: WebResource;\n auth?: WebAuthenticationRule;\n}', }, { name: 'WebResultView', @@ -10730,7 +10778,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'WebRoute', - declaration: 'export interface WebRoute {\n kind: WebRouteKind;\n path: string;\n handler: (req: IncomingMessage, res: ServerResponse) => void | Promise;\n}', + declaration: 'export interface WebRoute {\n kind: WebRouteKind;\n path: string;\n handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise;\n auth?: WebAuthenticationRule;\n}', }, { name: 'WebRouteKind', @@ -10770,7 +10818,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'WebUpgradeRoute', - declaration: 'export interface WebUpgradeRoute {\n path: string;\n handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void | Promise;\n}', + declaration: 'export interface WebUpgradeRoute {\n path: string;\n handler: (req: IncomingMessage, socket: Duplex, head: Buffer, peer?: PeerScope) => void | Promise;\n auth?: WebAuthenticationRule;\n}', }, { name: 'WeeklyInput', diff --git a/packages/host/authentication-desktop/README.i18n.yaml b/packages/host/authentication-desktop/README.i18n.yaml new file mode 100644 index 0000000000..881095823d --- /dev/null +++ b/packages/host/authentication-desktop/README.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/host/authentication-desktop/README.md +/: + en: 31484da58ba0fa12 + zh: 1ba978273620bf0f +/deepseek-ai-dsh-host-authentication-desktop: + en: 9f56b15c58dca9eb + zh: 77dd9cacf037d6ac +/deepseek-ai-dsh-host-authentication-desktop/summary: + en: 2beda6371f4c6463 + zh: afdb9ecabd6f3eb1 +/deepseek-ai-dsh-host-authentication-desktop/table-of-contents: + en: d152484eb41ac6b4 + zh: f84d50f3f752145c +/deepseek-ai-dsh-host-authentication-desktop/use-this-package: + en: 9ab26d23b93107ab + zh: 35f2606748529d85 +/deepseek-ai-dsh-host-authentication-desktop/understand-the-implementation: + en: 02ac97d0f273bd76 + zh: 6285bb9e911cec3a +/deepseek-ai-dsh-host-authentication-desktop/further-exploration: + en: 6b669dabd7d42226 + zh: bfac21ab8d8cefaa +/deepseek-ai-dsh-host-authentication-desktop/model-experience: + en: afca588fd56333d6 + zh: 3b7c196ac96f56d9 +/deepseek-ai-dsh-host-authentication-desktop/model-experience/kv-cache-effect: + en: bc510c5c25c0204f + zh: 55366b46ba23f1eb +/deepseek-ai-dsh-host-authentication-desktop/known-limitations-and-deferred-work: + en: be88a23eed13dc51 + zh: 9b399741e8be49c3 +/deepseek-ai-dsh-host-authentication-desktop/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/host/authentication-desktop/README.md b/packages/host/authentication-desktop/README.md new file mode 100644 index 0000000000..61bd94d116 --- /dev/null +++ b/packages/host/authentication-desktop/README.md @@ -0,0 +1,82 @@ +--- +kind: package-reference +description: "Authenticate Desktop requests with a private, in-memory credential without exposing it to the renderer." +--- + +# @deepseek-ai/dsh-host-authentication-desktop + +English | [中文](README.zh.md) + +## Summary + +Desktop can access its Host with a private credential without a browser-token exchange. The credential flows only between the Electron main process and its owned Host, never into the browser cookie jar; the renderer receives ordinary startup data only. All authenticated Desktop requests share owner access for that Desktop lifetime. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The Desktop startup owner mounts the plugin through Cordis after receiving its private parent credential. It injects `connection` for Peer creation and `connection.authentication` for Provider registration; the Connection plugin provides both. Configuration is supplied in memory rather than written to a profile or settings file. + +| Field | Default | Meaning | +|---|---|---| +| `readSecret` | required | Function returning the credential already validated on the private parent IPC channel | + +The provider accepts one `dsh-desktop-session` Cookie value matching its credential. Duplicate values, malformed credentials and mismatches are rejected. Successful HTTP and WebSocket admission reuse its existing Peer. Disposing this plugin removes its provider registration and ends that Peer through the normal Connection lifecycle. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The Desktop parent process generates and privately delivers the credential. The Host application's IPC receiver validates the handshake; its startup entry authenticates through ConnectionAuthentication before publishing the page injections. Both ends use the fixed Cookie name `dsh-desktop-session` and the value `=`. The Cordis plugin owns credential verification and Peer creation. Desktop owns Host address validation and request forwarding, including origin checks and credential attachment. It supplies the process channel, mounts the plugin, and publishes its single ready response. ConnectionAuthentication owns the Provider registry and verification; Connection owns Peer creation and transport. + +The [plugin entry](src/index.ts) exports the ordinary `name`, `inject`, and `apply` members; `Config` is a TypeScript interface. Token and Desktop register through the same ConnectionAuthentication service, with neither provider depending on the other. + +
+ +----- + + +## Further Exploration + +- [Desktop application](../../../apps/desktop/README.md) — parent process and Host startup. +- [Connection](../../client/connection/README.md) — ConnectionAuthentication registration and Peer lifecycle. +- [Token authentication](../authentication-token/README.md) — browser launch-token authentication. + + +## Model Experience + +None, as authentication introduces no model-visible input. + +#### KV Cache effect + +None; authentication does not modify model requests. + +## Known Limitations and Deferred Work + + + +- The plugin is a Desktop startup component. Its input requires a private credential validated by the process owner, and its shared Peer grants owner access for that Desktop lifetime. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/host/authentication-desktop/README.zh.md b/packages/host/authentication-desktop/README.zh.md new file mode 100644 index 0000000000..33b5eb5df5 --- /dev/null +++ b/packages/host/authentication-desktop/README.zh.md @@ -0,0 +1,82 @@ +--- +kind: package-reference +description: "使用仅存于内存的私有凭据认证 Desktop 请求,不向 renderer 暴露凭据。" +--- + +# @deepseek-ai/dsh-host-authentication-desktop + +[English](README.md) | 中文 + +## 概述 + +Desktop 可以使用私有凭据访问 Host,无需浏览器 Token 交换。凭据仅在 Electron 主进程与其自有 Host 之间流动,绝不进入浏览器 Cookie 存储;renderer 只收到普通启动数据。所有认证成功的 Desktop 请求在该 Desktop 生命周期中共享 owner 权限。 + +## 目录 + +- [使用](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用 + +Desktop 启动 owner 收到父进程的私有凭据后,通过 Cordis 挂载插件。它注入 `connection` 创建 Peer,通过 `connection.authentication` 注册 Provider;Connection 插件提供这两个服务。配置仅在内存中交付,而非写入 profile 或设置文件。 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `readSecret` | 必填 | 返回已在父进程私有 IPC 通道上通过校验的凭据的函数 | + +Provider 接受单个与自身凭据匹配的 `dsh-desktop-session` Cookie 值。重复值、格式错误和不匹配凭据均拒绝。认证成功的 HTTP 和 WebSocket 准入复用已有 Peer。插件卸载移除 Provider 注册,并通过原 Connection 生命周期结束该 Peer。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +Desktop 父进程生成并私下交付凭据。Host 应用的 IPC 接收器校验握手;启动入口在发布页面注入前通过 ConnectionAuthentication 完成认证。两端均使用固定 Cookie 名 `dsh-desktop-session` 和 `=` 格式。Cordis 插件拥有凭据验证和 Peer 创建。Desktop 拥有 Host 地址校验和请求转发,包括来源检查与凭据附加。它提供进程通道、挂载插件并发布单条 ready 响应。ConnectionAuthentication 拥有 Provider 注册表与验证;Connection 拥有 Peer 创建与传输。 + +[插件入口](src/index.ts)导出标准的 `name`、`inject`、`apply` 成员;`Config` 是 TypeScript 接口。Token 和 Desktop 通过相同的 ConnectionAuthentication 服务注册,两者互不依赖。 + +
+ +----- + + +## 进一步探索 + +- [Desktop 应用](../../../apps/desktop/README.zh.md)——父进程与 Host 启动。 +- [Connection](../../client/connection/README.zh.md)——ConnectionAuthentication 注册与 Peer 生命周期。 +- [Token 认证](../authentication-token/README.zh.md)——浏览器启动 Token 认证。 + + +## 模型体验 + +无,因为认证不增加模型可见输入。 + +#### KV Cache 影响 + +无;认证不修改模型请求。 + +## 已知限制与后续工作 + + + +- 本插件是 Desktop 启动组件。输入必须是进程 owner 已验证的私有凭据,共享 Peer 在该 Desktop 生命周期中授予 owner 权限。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/host/authentication-desktop/locale/de.json b/packages/host/authentication-desktop/locale/de.json new file mode 100644 index 0000000000..3831484509 --- /dev/null +++ b/packages/host/authentication-desktop/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Desktop-Authentifizierung", + "description": "Authentifiziert Desktop-Anfragen mit einem privaten Zugangsschlüssel, den sich der übergeordnete Prozess und der Host-Prozess teilen." + } +} diff --git a/packages/host/authentication-desktop/locale/en.json b/packages/host/authentication-desktop/locale/en.json new file mode 100644 index 0000000000..625305a7b8 --- /dev/null +++ b/packages/host/authentication-desktop/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Desktop authentication", + "description": "Authenticate Desktop requests with a private credential shared by the parent and Host processes." + } +} diff --git a/packages/host/authentication-desktop/locale/es.json b/packages/host/authentication-desktop/locale/es.json new file mode 100644 index 0000000000..d05ca3a670 --- /dev/null +++ b/packages/host/authentication-desktop/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Autenticación de Desktop", + "description": "Autentica las solicitudes de Desktop con una credencial privada compartida por el proceso padre y el proceso Host." + } +} diff --git a/packages/host/authentication-desktop/locale/fr.json b/packages/host/authentication-desktop/locale/fr.json new file mode 100644 index 0000000000..f2ab4da688 --- /dev/null +++ b/packages/host/authentication-desktop/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Authentification Desktop", + "description": "Authentifie les requêtes Desktop avec un identifiant privé partagé par le processus parent et le processus Host." + } +} diff --git a/packages/host/authentication-desktop/locale/ja.json b/packages/host/authentication-desktop/locale/ja.json new file mode 100644 index 0000000000..0fc9853656 --- /dev/null +++ b/packages/host/authentication-desktop/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Desktop 認証", + "description": "親プロセスと Host プロセスで共有する非公開の認証情報を使って、Desktop のリクエストを認証します。" + } +} diff --git a/packages/host/authentication-desktop/locale/pt.json b/packages/host/authentication-desktop/locale/pt.json new file mode 100644 index 0000000000..8a196343a2 --- /dev/null +++ b/packages/host/authentication-desktop/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Autenticação do Desktop", + "description": "Autentica solicitações do Desktop com uma credencial privada compartilhada pelo processo pai e pelo processo Host." + } +} diff --git a/packages/host/authentication-desktop/locale/ru.json b/packages/host/authentication-desktop/locale/ru.json new file mode 100644 index 0000000000..8a8fb0d23d --- /dev/null +++ b/packages/host/authentication-desktop/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Аутентификация Desktop", + "description": "Аутентифицирует запросы Desktop с помощью закрытых учётных данных, общих для родительского процесса и процесса Host." + } +} diff --git a/packages/host/authentication-desktop/locale/zh.json b/packages/host/authentication-desktop/locale/zh.json new file mode 100644 index 0000000000..c21c21f23f --- /dev/null +++ b/packages/host/authentication-desktop/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Desktop 认证", + "description": "使用父进程与 Host 进程共享的私有凭据认证 Desktop 请求。" + } +} diff --git a/packages/host/authentication-desktop/package.json b/packages/host/authentication-desktop/package.json new file mode 100644 index 0000000000..a44c3d404e --- /dev/null +++ b/packages/host/authentication-desktop/package.json @@ -0,0 +1,38 @@ +{ + "name": "@deepseek-ai/dsh-host-authentication-desktop", + "description": "Desktop private-channel authentication provider", + "version": "0.2.2-rc.2", + "publishConfig": { "access": "public" }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/host/authentication-desktop" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./locale/de.json": "./locale/de.json", + "./locale/en.json": "./locale/en.json", + "./locale/es.json": "./locale/es.json", + "./locale/fr.json": "./locale/fr.json", + "./locale/ja.json": "./locale/ja.json", + "./locale/pt.json": "./locale/pt.json", + "./locale/ru.json": "./locale/ru.json", + "./locale/zh.json": "./locale/zh.json", + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": ["locale/de.json", "locale/en.json", "locale/es.json", "locale/fr.json", "locale/ja.json", "locale/pt.json", "locale/ru.json", "locale/zh.json", "lib/index.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", "src"], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-connection": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-connection": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" + } +} diff --git a/packages/host/authentication-desktop/src/index.ts b/packages/host/authentication-desktop/src/index.ts new file mode 100644 index 0000000000..06ff069a5d --- /dev/null +++ b/packages/host/authentication-desktop/src/index.ts @@ -0,0 +1,42 @@ +/** Desktop's private credential verifier, registered as an ordinary Connection provider. */ +import { timingSafeEqual } from 'node:crypto' +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-client-connection' + +/** Stable plugin name. */ +export const name = 'host-authentication-desktop' +/** Connection creates Peers; ConnectionAuthentication owns credential verifiers. */ +export const inject = ['connection', 'connection.authentication'] + +/** In-memory startup input supplied by the Desktop process owner. */ +export interface Config { + /** Read the credential already validated on the private parent IPC channel. */ + readSecret: () => string +} + +/** + * Own one Desktop Peer and the verifier accepting its private credential. + * The credential flows only between the Electron main process and its owned Host, never into the browser cookie jar. + * @param ctx - plugin scope owning the Peer and registration. + * @param config - in-memory credential reader from the Desktop startup owner. + */ +export function apply(ctx: Context, config: Config): void { + const expected = Buffer.from(config.readSecret(), 'ascii') + const peer = ctx.connection.createPeer({ principal: { kind: 'owner' } }) + ctx.connection.authentication.register({ + authenticate(request) { + const cookie = request.headers instanceof Headers ? request.headers.get('cookie') : request.headers.cookie + if (typeof cookie !== 'string') return undefined + let value: string | undefined + for (const part of cookie.split(';')) { + const equals = part.indexOf('=') + if (equals < 0 || part.slice(0, equals).trim() !== 'dsh-desktop-session') continue + if (value !== undefined) return undefined + value = part.slice(equals + 1).trim() + } + if (value === undefined || !/^[A-Za-z0-9_-]{43}$/u.test(value)) return undefined + const actual = Buffer.from(value, 'ascii') + return actual.length === expected.length && timingSafeEqual(actual, expected) ? peer : undefined + }, + }) +} diff --git a/packages/host/authentication-desktop/tests/plugin.host.spec.ts b/packages/host/authentication-desktop/tests/plugin.host.spec.ts new file mode 100644 index 0000000000..7b231c56aa --- /dev/null +++ b/packages/host/authentication-desktop/tests/plugin.host.spec.ts @@ -0,0 +1,28 @@ +/** Desktop authentication is owned by its mounted plugin fiber. */ +import { Context } from '@deepseek-ai/cordis' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import { expect, it, onTestFinished } from 'vitest' +import * as DesktopAuthentication from '../src/index.ts' + +it('owns the provider and shared Peer while retaining only an in-memory credential reader in config', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(Connection).await() + const secret = 'A'.repeat(43) + const config = { readSecret: () => secret } + expect(JSON.stringify(config)).toBe('{}') + const plugin = ctx.plugin(DesktopAuthentication, config) + await plugin.await() + const request = { headers: { cookie: `dsh-desktop-session=${secret}` } } + const first = ctx.connection.authentication.authenticate(request) + if ('rejection' in first) throw new Error('Desktop provider did not activate') + expect(first.peer).not.toBe(ctx.connection.browserPeer) + expect(ctx.connection.authentication.authenticate(request)).toEqual({ peer: first.peer }) + expect(ctx.connection.authentication.authenticate({ headers: new Headers(request.headers) })).toEqual({ peer: first.peer }) + expect(ctx.connection.authentication.authenticate({ headers: new Headers() })).toEqual({ rejection: 401 }) + expect(ctx.connection.authentication.authenticate({ headers: new Headers({ cookie: 'dsh-desktop-session=wrong' }) })).toEqual({ rejection: 401 }) + expect(ctx.connection.authentication.authenticate({ headers: { cookie: 'dsh-desktop-session=wrong' } })).toEqual({ rejection: 401 }) + await plugin.dispose() + expect(first.peer.signal.aborted).toBe(true) + expect(ctx.connection.authentication.authenticate(request)).toEqual({ rejection: 401 }) +}) diff --git a/packages/host/authentication-desktop/tsconfig.json b/packages/host/authentication-desktop/tsconfig.json new file mode 100644 index 0000000000..646c78be0b --- /dev/null +++ b/packages/host/authentication-desktop/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { "rootDir": "src", "outDir": "lib/types" }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cordis" }, + { "path": "../../client/connection/tsconfig.host.json" } + ] +} diff --git a/packages/host/authentication-token/README.i18n.yaml b/packages/host/authentication-token/README.i18n.yaml new file mode 100644 index 0000000000..fabbeee921 --- /dev/null +++ b/packages/host/authentication-token/README.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/host/authentication-token/README.md +/: + en: 887c38cd3455317c + zh: 838eaef05fb7666d +/deepseek-ai-dsh-host-authentication-token: + en: debb5f97934d02dc + zh: f9360a99b39be788 +/deepseek-ai-dsh-host-authentication-token/summary: + en: ad43733f78bfc6b1 + zh: 1d963c3c2666b7a8 +/deepseek-ai-dsh-host-authentication-token/table-of-contents: + en: d152484eb41ac6b4 + zh: 6e85873f6f5f222a +/deepseek-ai-dsh-host-authentication-token/use-this-package: + en: 3d20e5d3cb713786 + zh: 0bf29d01c2dddfaa +/deepseek-ai-dsh-host-authentication-token/understand-the-implementation: + en: 6a5250377ab73cd3 + zh: b1c6a2f94f19efa0 +/deepseek-ai-dsh-host-authentication-token/further-exploration: + en: 51496d45cfab2cb5 + zh: bd7a00185da780af +/deepseek-ai-dsh-host-authentication-token/model-experience: + en: 203cd258d4e8a181 + zh: 740c4f6410ae6919 +/deepseek-ai-dsh-host-authentication-token/model-experience/kv-cache-effect: + en: bc510c5c25c0204f + zh: 55366b46ba23f1eb +/deepseek-ai-dsh-host-authentication-token/known-limitations-and-deferred-work: + en: 7700f421f2c53016 + zh: 3d711811688b26de +/deepseek-ai-dsh-host-authentication-token/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: 8ec3e73528ddb1a6 diff --git a/packages/host/authentication-token/README.md b/packages/host/authentication-token/README.md new file mode 100644 index 0000000000..080fe015b8 --- /dev/null +++ b/packages/host/authentication-token/README.md @@ -0,0 +1,92 @@ +--- +description: "Sign in through the default launch token and retain browser access through authority-bound Cookies." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-host-authentication-token + +English | [中文](README.zh.md) + +## Summary + +Open the tokenized launch URL to sign a browser Cookie, then continue accessing the application with that Cookie. API clients exchange the same process token through `/connect` for their independent connection credentials. The plugin preserves the default Cookie format and signing-key record while registering through the common ConnectionAuthentication service. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this function plugin beside Connection and Credentials. It also injects `connection.authentication`, which the Connection plugin provides. A WebServer adds HTTP exchange routes; the authentication provider also works in compositions without a Web listener. The plugin contributes a signed `dsh web` entry through `webserver/entry-url`; WebApp owns printing and browser opening. The package's runtime entry exports `name`, `inject`, `Config`, and `apply`. + +| Field | Default | Meaning | +|---|---|---| +| `cookieMaxAgeDays` | `30` | Absolute browser and API Cookie lifetime in days | + +Configure `printUrl` and `openBrowser` on the WebApp runtime, not this plugin. Authentication remains available without startup publication. + +A root request carrying the launch-token query is handled by the original token exchange: successful `GET /` returns 303 with a Cookie and redirects to `./`; invalid credentials return 401. Requests on other paths continue to their route owner. When WebApp collects entries after readiness, this plugin appends its process token to the supplied base URL while preserving its authority, path, and other query fields. The contributed entry is eligible for automatic opening. Token neither reads WebApp services nor owns printing, readiness, or the native browser opener. + +Browser v1 Cookies authenticate to one shared Peer owned by this plugin. `/connect` declares anonymous route admission: Connection checks the source, then the handler verifies the launch token, creates an API Peer, and signs its ID in a v2 Cookie. A valid v2 Cookie authenticates pages and API requests through the same Provider. The Peer's principal and RemoteAccess determine permissions; there is no page/API purpose level. Token permits one `/api/remote.mux` Socket per API Peer: duplicate attachment returns 409 without revoking the first connection. Closing that Socket revokes the credential synchronously, then disposes the Peer; later requests using that Cookie are refused. Other upgrade routes, including Inspector CDP, neither claim the Peer nor revoke it on closure. + +The signing secret remains the `client-connection/browser-session` grant record in Credentials. Cookie names, signed audiences, expiry validation, and the listener-controlled `Secure` attribute follow the existing protocol. Reloading retains this root application's launch token and still-valid Cookies while creating a new plugin-owned shared Peer. Token activation failure may leave the application running without this verifier; it does not permit unauthenticated access to protected routes. Desktop can mount this Provider alongside its private-credential Provider. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The plugin prepares its signer, creates a shared Peer through Connection, and registers through `ctx.connection.authentication` a verifier returning that Peer for v1 Cookies or resolving a verified v2 ID through its own API Peer map. It uses the same verification for pages and API calls. Its WebServer request listener owns root token exchange, while an anonymous exact route owns `/connect`. + +Beside that route, a `webserver/upgrade` listener delegates non-mux paths and recognizes owned API Peers on `/api/remote.mux` by `apiPeers.get(peer.id) === peer`; shared browser Peers and other Providers delegate with `next()`. This listener runs after route admission and before protocol handling. Socket close, error, and upgrade failure revoke the API credential before asynchronous disposal. Peer disposal also closes its Socket. Cleanup is idempotent; the Web integration scope removes its listeners, revokes its API credentials, destroys only its owned API Sockets, and awaits Socket closure and Peer cleanup. Late middleware cannot restore a revoked Peer. A synchronous `webserver/entry-url` listener contributes the signed URL; its event and entry type are declared by WebServer, without a dependency on the WebApp bundle. + +The original launch-token lifetime and Cookie algorithms stay in the internal [BrowserAuth implementation](src/browser-auth.ts). The [plugin entry](src/index.ts) supplies the Connection, ConnectionAuthentication, and WebServer integration, and [internal types](src/types.ts) describe the HTTP operations used by the signer. + +
+ +----- + + +## Further Exploration + +- [Connection](../../client/connection/README.md) — ConnectionAuthentication registration and existing Peer lifecycle. +- [WebServer](../webserver/README.md) — HTTP routes and request events. +- [Credentials](../../credentials/credentials/README.md) — persistent signing-key records. + + +## Model Experience + +None, as the plugin authenticates HTTP callers and contributes no model input. + +#### KV Cache effect + +None; authentication does not modify model requests. + +## Known Limitations and Deferred Work + + + +- Browser Cookies share one plugin-owned Peer; ending the plugin scope ends its live connections together. +- Plain HTTP transports bearer Cookies without encryption. Listener TLS determines the Cookie's `Secure` attribute. +- The token middleware owns only the root token exchange. Other HTML or product paths keep their route owner's handling, including any token query on those paths. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/host/authentication-token/README.zh.md b/packages/host/authentication-token/README.zh.md new file mode 100644 index 0000000000..f0eb7e1691 --- /dev/null +++ b/packages/host/authentication-token/README.zh.md @@ -0,0 +1,92 @@ +--- +description: "通过默认启动 Token 登录,并使用绑定 authority 的 Cookie 持续访问应用。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-host-authentication-token + +[English](README.md) | 中文 + +## 概述 + +打开带 Token 的启动地址以签发浏览器 Cookie,随后携带该 Cookie 继续访问应用。API 客户端通过 `/connect` 交换同一个进程 Token,取得独立连接凭据。插件保留默认 Cookie 格式与签名密钥记录,并通过通用 ConnectionAuthentication 服务注册。 + +## 目录 + +- [使用方式](#use-this-package) +- [实现说明](#understand-the-implementation) +- [延伸阅读](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用方式 + +将此函数插件与 Connection 和 Credentials 一同挂载。它还注入由 Connection 插件提供的 `connection.authentication`。存在 WebServer 时提供 HTTP 交换路由;认证 Provider 也能用于没有 Web 监听器的组合。插件通过 `webserver/entry-url` 贡献带签名的 `dsh web` 入口;打印与浏览器打开归 WebApp。包运行入口导出 `name`、`inject`、`Config` 和 `apply`。 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `cookieMaxAgeDays` | `30` | 浏览器与 API Cookie 的绝对有效期,单位为天 | + +在 WebApp runtime 上配置 `printUrl` 与 `openBrowser`,而非本插件。不发布启动入口时,认证仍然可用。 + +携带启动 Token query 的根路径请求由原 Token 交换处理:成功的 `GET /` 返回303、写入 Cookie,并重定向到 `./`;无效凭据返回401。其他路径的请求交给其路由 owner。WebApp 就绪后收集入口时,本插件向传入的基地址追加进程 Token,同时保留 authority、路径与其他 query 字段。贡献的入口允许自动打开。Token 不读取 WebApp 服务,也不拥有打印、就绪判断或原生浏览器打开器。 + +浏览器 v1 Cookie 认证为本插件拥有的共享 Peer。`/connect` 声明匿名路由准入:Connection 检查来源,handler 随后验证启动 Token、创建 API Peer,并在 v2 Cookie 中签入其 ID。有效 v2 Cookie 通过同一 Provider 认证页面与 API 请求。Peer 的 principal 与 RemoteAccess 决定权限,不区分页面/API purpose 等级。Token 限制每个 API Peer 只有一条 `/api/remote.mux` Socket;重复关联返回409,不撤销首条连接。该 Socket 关闭时先同步撤销凭据,再释放 Peer;后续使用该 Cookie 的请求被拒绝。其他升级路由(包括 Inspector CDP)不认领该 Peer,也不在关闭时撤销它。 + +签名密钥仍使用 Credentials 的 `client-connection/browser-session` grant 记录。Cookie 名称、签名 audience、有效期验证及监听器决定的 `Secure` 属性遵循既有协议。重载保留根应用的启动 Token 与尚有效 Cookie,同时创建新的插件共享 Peer。Token 激活失败允许应用在缺少此验证器时继续运行,但不允许未认证访问受保护路由。Desktop 可以同时挂载本 Provider 与私有凭据 Provider。 + +----- + + +## 实现说明 + +
+实现内部说明 — 点击展开 + +插件准备签发器,通过 Connection 创建共享 Peer,并通过 `ctx.connection.authentication` 注册验证器:v1 Cookie 返回共享 Peer,v2 ID 验签后通过插件自己的 API Peer 映射表解析。页面与 API 调用使用相同验证。WebServer 请求监听器拥有根 Token 交换,匿名精确路由拥有 `/connect`。 + +该路由旁的 `webserver/upgrade` 监听器委派非 mux 路径,并在 `/api/remote.mux` 上按 `apiPeers.get(peer.id) === peer` 识别自己拥有的 API Peer;浏览器共享 Peer 与其他 Provider 调用 `next()` 委派。此监听器位于路由准入后、协议处理前。Socket 关闭、错误及 upgrade 失败时,在异步释放前撤销 API 凭据。Peer 释放也会关闭其 Socket。清理幂等;Web 接线作用域移除监听器、撤销自己的 API 凭据、仅销毁自己拥有的 API Socket,并等待 Socket 关闭与 Peer 清理。迟到的中间件不能恢复已撤销的 Peer。同步 `webserver/entry-url` 监听器贡献带签名的 URL;事件和入口类型由 WebServer 声明,无需依赖 WebApp bundle。 + +原启动 Token 寿命与 Cookie 算法保留在内部 [BrowserAuth 实现](src/browser-auth.ts)。[插件入口](src/index.ts)负责 Connection、ConnectionAuthentication 与 WebServer 接线,[内部类型](src/types.ts)描述签发器使用的 HTTP 操作。 + +
+ +----- + + +## 延伸阅读 + +- [Connection](../../client/connection/README.zh.md) — ConnectionAuthentication 注册与既有 Peer 生命周期。 +- [WebServer](../webserver/README.zh.md) — HTTP 路由与请求事件。 +- [Credentials](../../credentials/credentials/README.zh.md) — 持久签名密钥记录。 + + +## 模型体验 + +无,因为插件认证 HTTP 调用方,不贡献模型输入。 + +#### KV Cache 影响 + +无;认证不修改模型请求。 + +## 已知限制与后续工作 + + + +- 浏览器 Cookie 共用一个插件 Peer;结束插件作用域时,其存活连接一同结束。 +- 明文 HTTP 不加密 bearer Cookie。Cookie 的 `Secure` 属性由监听器 TLS 决定。 +- Token 中间件只拥有根路径交换。其他 HTML 或产品路径仍由路由 owner 处理,包括这些路径上的 token query。 + + +### 开发备注 + +
+维护者工作上下文 — 点击展开 + +无。 + +
diff --git a/packages/host/authentication-token/locale/de.json b/packages/host/authentication-token/locale/de.json new file mode 100644 index 0000000000..b095ef4c29 --- /dev/null +++ b/packages/host/authentication-token/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Token-Authentifizierung", + "description": "Tauscht ein Start-Token gegen Browserzugriff ein und authentifiziert Anfragen mit signierten Cookies." + } +} diff --git a/packages/host/authentication-token/locale/en.json b/packages/host/authentication-token/locale/en.json new file mode 100644 index 0000000000..0e52552c43 --- /dev/null +++ b/packages/host/authentication-token/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Token authentication", + "description": "Exchange a launch token for browser access and authenticate requests with signed Cookies." + } +} diff --git a/packages/host/authentication-token/locale/es.json b/packages/host/authentication-token/locale/es.json new file mode 100644 index 0000000000..c0a580f909 --- /dev/null +++ b/packages/host/authentication-token/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Autenticación por token", + "description": "Intercambia un token de inicio por acceso desde el navegador y autentica las solicitudes con cookies firmadas." + } +} diff --git a/packages/host/authentication-token/locale/fr.json b/packages/host/authentication-token/locale/fr.json new file mode 100644 index 0000000000..c71213be6e --- /dev/null +++ b/packages/host/authentication-token/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Authentification par jeton", + "description": "Échange un jeton de lancement contre un accès depuis le navigateur et authentifie les requêtes avec des cookies signés." + } +} diff --git a/packages/host/authentication-token/locale/ja.json b/packages/host/authentication-token/locale/ja.json new file mode 100644 index 0000000000..93ab63e1db --- /dev/null +++ b/packages/host/authentication-token/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Token 認証", + "description": "起動 Token をブラウザーのアクセス権と交換し、署名付き Cookie でリクエストを認証します。" + } +} diff --git a/packages/host/authentication-token/locale/pt.json b/packages/host/authentication-token/locale/pt.json new file mode 100644 index 0000000000..aaa61d2717 --- /dev/null +++ b/packages/host/authentication-token/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Autenticação por token", + "description": "Troca um token de inicialização por acesso pelo navegador e autentica solicitações com cookies assinados." + } +} diff --git a/packages/host/authentication-token/locale/ru.json b/packages/host/authentication-token/locale/ru.json new file mode 100644 index 0000000000..ecbbdd3371 --- /dev/null +++ b/packages/host/authentication-token/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Аутентификация по токену", + "description": "Обменивает токен запуска на доступ из браузера и аутентифицирует запросы с помощью подписанных файлов cookie." + } +} diff --git a/packages/host/authentication-token/locale/zh.json b/packages/host/authentication-token/locale/zh.json new file mode 100644 index 0000000000..9c53817a56 --- /dev/null +++ b/packages/host/authentication-token/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Token 认证", + "description": "通过启动 Token 换取浏览器访问凭据,并使用签名 Cookie 认证请求。" + } +} diff --git a/packages/host/authentication-token/package.json b/packages/host/authentication-token/package.json new file mode 100644 index 0000000000..317fcf8671 --- /dev/null +++ b/packages/host/authentication-token/package.json @@ -0,0 +1,48 @@ +{ + "name": "@deepseek-ai/dsh-host-authentication-token", + "description": "Default token authentication provider and HTTP cookie exchange", + "version": "0.2.2-rc.2", + "publishConfig": { "access": "public" }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/host/authentication-token" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./locale/de.json": "./locale/de.json", + "./locale/en.json": "./locale/en.json", + "./locale/es.json": "./locale/es.json", + "./locale/fr.json": "./locale/fr.json", + "./locale/ja.json": "./locale/ja.json", + "./locale/pt.json": "./locale/pt.json", + "./locale/ru.json": "./locale/ru.json", + "./locale/zh.json": "./locale/zh.json", + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": ["locale/de.json", "locale/en.json", "locale/es.json", "locale/fr.json", "locale/ja.json", "locale/pt.json", "locale/ru.json", "locale/zh.json", "lib/index.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", "src"], + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-connection": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", + "@deepseek-ai/dsh-client-connection": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-credentials-local": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-host-frontend-static": "workspace:*" + } +} diff --git a/packages/client/connection/src/browser-auth.ts b/packages/host/authentication-token/src/browser-auth.ts similarity index 95% rename from packages/client/connection/src/browser-auth.ts rename to packages/host/authentication-token/src/browser-auth.ts index 5c8594df6f..77813fda48 100644 --- a/packages/client/connection/src/browser-auth.ts +++ b/packages/host/authentication-token/src/browser-auth.ts @@ -2,14 +2,15 @@ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto' import type { PeerId } from '@deepseek-ai/dsh-typert-protocol' -import { CONNECT_PATH, type ConnectionInteractions } from './connect-protocol.ts' +import { CONNECT_PATH } from '@deepseek-ai/dsh-client-connection' +import type { ConnectionInteractions } from './types.ts' import { credentialKey } from '@deepseek-ai/dsh-credentials' import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials' import type { ConnectionIndexRequest, ConnectionIndexResponse, ConnectionTrustRequest, -} from './rpc.ts' +} from './types.ts' const AUTH_RECORD_KEY = credentialKey('client-connection', 'browser-session') const DAY_MILLISECONDS = 24 * 60 * 60 * 1000 @@ -98,11 +99,11 @@ function storedSecret(record: CredentialRecord | undefined): Buffer | undefined if (record === undefined) return undefined if (record.kind !== 'grant' || !isRecord(record.payload) || record.payload.version !== STORED_SECRET_VERSION) { - throw new Error('client-connection: browser-session credential record has an unsupported format') + throw new Error('host-authentication-token: browser-session credential record has an unsupported format') } const secret = canonicalSecret(record.payload.secret) if (secret === undefined) { - throw new Error('client-connection: browser-session credential record has an invalid secret') + throw new Error('host-authentication-token: browser-session credential record has an invalid secret') } return secret } @@ -193,14 +194,14 @@ async function initializeSecret(credentials: CredentialProvider): Promise = z.object({ + cookieMaxAgeDays: z.natural().min(1).default(30), +}) + +/** + * Register the token provider and its optional Web transport integration. + * @param ctx - plugin scope owning the shared Peer and registrations. + * @param config - validated browser and API cookie lifetime. + */ +export async function apply(ctx: Context, config: Config): Promise { + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, config.cookieMaxAgeDays) + const peer = ctx.connection.createPeer({ principal: { kind: 'owner' } }) + const apiPeers = new Map() + ctx.connection.authentication.register({ + authenticate(request) { + const secure = ctx.get('webServer')?.protocol === 'https:' + if (auth.isAuthenticated(request, secure)) return peer + const id = auth.authenticateApi(request, secure) + return id === undefined ? undefined : apiPeers.get(id) + }, + }) + ctx.inject(['webServer'], (webCtx) => { + let active = true + const sockets = new Map Promise>() + webCtx.effect(() => async () => { + active = false + apiPeers.clear() + await Promise.all([...sockets.values()].map(release => release())) + }, 'host-authentication-token: API sockets') + webCtx.on('webserver/request', async (request, response, next) => { + const facts: ConnectionTrustRequest = request + if (facts.socket?.destroyed || response.destroyed || facts.signal?.aborted) return + if (!active) { await next(); return } + const url = new URL(request.url ?? '/', 'http://dsh.invalid') + if (url.pathname !== '/' || !url.searchParams.has('token')) { + await next() + return + } + auth.authorizeIndex(request, response, webCtx.webServer.protocol === 'https:') + }) + webCtx.effect(() => webCtx.webServer.register({ + kind: 'exact', path: CONNECT_PATH, auth: 'anonymous', + handler(request, response) { + const facts: ConnectionTrustRequest = request + if (facts.socket?.destroyed || response.destroyed || facts.signal?.aborted) return + if (!active) { + response.writeHead(401) + response.end('unauthorized') + return + } + auth.authorizeConnect(request, response, webCtx.webServer.protocol === 'https:', (interactions) => { + const apiPeer = webCtx.connection.createPeer({ principal: { kind: 'owner' }, interactions }) + apiPeers.set(apiPeer.id, apiPeer) + apiPeer.ctx.effect(() => () => { apiPeers.delete(apiPeer.id) }, 'authentication-token: API credential') + return apiPeer.id + }) + }, + }), 'host-authentication-token: API connect') + webCtx.on('webserver/upgrade', async (request, socket, _head, admittedPeer, next) => { + if (admittedPeer === undefined) { await next(); return } + if (new URL(request.url ?? '/', 'http://dsh.invalid').pathname !== '/api/remote.mux') { + await next() + return + } + if (apiPeers.get(admittedPeer.id) !== admittedPeer) { + if (auth.authenticateApi(request, webCtx.webServer.protocol === 'https:') === admittedPeer.id) { + socket.destroy() + return + } + await next() + return + } + if (!active || admittedPeer.signal.aborted) { socket.destroy(); return } + if (sockets.has(admittedPeer)) { + socket.end([ + 'HTTP/1.1 409 Conflict', + 'Connection: close', + 'Content-Type: text/plain; charset=utf-8', + 'Content-Length: 8', + '', + 'conflict', + ].join('\r\n')) + return + } + const closed = Promise.withResolvers() + let released: Promise | undefined + const release = (): Promise => { + if (released !== undefined) return released + // Revocation precedes asynchronous Peer and stream cleanup. + apiPeers.delete(admittedPeer.id) + socket.destroy() + released = Promise.all([ + closed.promise, + admittedPeer.dispose().catch((error: unknown) => { + console.error('[host-authentication-token] Peer release failed:', error) + }), + ]).then(() => { + sockets.delete(admittedPeer) + void disposeSocket() + }) + return released + } + const failed = (): void => { void release() } + const finish = (): void => { + socket.removeListener('error', failed) + socket.removeListener('close', finish) + closed.resolve(undefined) + void release() + } + sockets.set(admittedPeer, release) + const disposeSocket = webCtx.effect(() => release, 'host-authentication-token: owned API socket') + admittedPeer.ctx.effect(() => { + socket.on('error', failed) + socket.once('close', finish) + return async () => { + apiPeers.delete(admittedPeer.id) + socket.destroy() + // Await only the transport: release itself awaits this Peer disposer. + await closed.promise + } + }, 'host-authentication-token: API socket') + if (socket.closed) finish() + if (socket.destroyed) { await release(); return } + try { + await next() + } catch (error) { + await release() + throw error + } + }) + }) + ctx.on('webserver/entry-url', (baseUrl, entries) => { + entries.push({ label: 'dsh web', url: auth.authenticatedUrl(baseUrl), open: true }) + }) +} diff --git a/packages/host/authentication-token/src/types.ts b/packages/host/authentication-token/src/types.ts new file mode 100644 index 0000000000..72b8854dcb --- /dev/null +++ b/packages/host/authentication-token/src/types.ts @@ -0,0 +1,18 @@ +/** Internal HTTP facts consumed by the default token and cookie implementation. */ +import type { ConnectionTrustRequest } from '@deepseek-ai/dsh-client-connection' + +/** Request metadata accepted by the token exchange. */ +export interface ConnectionIndexRequest extends ConnectionTrustRequest { + readonly method?: string | undefined + readonly url?: string | undefined +} + +/** Response operations used by the token implementation. */ +export interface ConnectionIndexResponse { + writeHead(status: number, headers?: Readonly>): unknown + end(body?: string): unknown +} + +export type { ConnectionTrustRequest } +/** Forwarded interaction participation for one API connection. */ +export type ConnectionInteractions = 'answer' | 'none' diff --git a/packages/client/connection/tests/browser-auth.host.spec.ts b/packages/host/authentication-token/tests/browser-auth.host.spec.ts similarity index 95% rename from packages/client/connection/tests/browser-auth.host.spec.ts rename to packages/host/authentication-token/tests/browser-auth.host.spec.ts index 7af762a1cd..010ef1b46f 100644 --- a/packages/client/connection/tests/browser-auth.host.spec.ts +++ b/packages/host/authentication-token/tests/browser-auth.host.spec.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { CredentialProvider } from '@deepseek-ai/dsh-credentials' import type { PeerId } from '@deepseek-ai/dsh-typert-protocol' import { BrowserAuth } from '../src/browser-auth.ts' -import type { ConnectionIndexRequest, ConnectionIndexResponse } from '../src/rpc.ts' +import type { ConnectionIndexRequest, ConnectionIndexResponse } from '../src/types.ts' import { RecordCredentials } from './browser-credentials.ts' function signedCookie(store: RecordCredentials, name: string, payload: unknown): string { @@ -49,7 +49,7 @@ function response(): { value: ConnectionIndexResponse; state: ResponseState } { } function credentials(store: RecordCredentials): CredentialProvider { - return store as unknown as CredentialProvider + return store } function createAuth( @@ -350,21 +350,21 @@ describe('BrowserAuth', () => { it('fails loud on an invalid owner record instead of replacing it', async () => { const unsupported = new RecordCredentials() unsupported.record = { kind: 'api-key', key: 'not-a-cookie-secret' } - await expect(createAuth(unsupported)).rejects.toThrow(/unsupported format/u) + await expect(createAuth(unsupported)).rejects.toThrow('host-authentication-token: browser-session credential record has an unsupported format') const malformed = new RecordCredentials() malformed.record = { kind: 'grant', payload: { version: 1, secret: 'short' } } - await expect(createAuth(malformed)).rejects.toThrow(/invalid secret/u) + await expect(createAuth(malformed)).rejects.toThrow('host-authentication-token: browser-session credential record has an invalid secret') const nonString = new RecordCredentials() nonString.record = { kind: 'grant', payload: { version: 1, secret: 42 } } - await expect(createAuth(nonString)).rejects.toThrow(/invalid secret/u) + await expect(createAuth(nonString)).rejects.toThrow('host-authentication-token: browser-session credential record has an invalid secret') const discarded = new RecordCredentials() discarded.discardWrites = true - await expect(createAuth(discarded)).rejects.toThrow(/was not created/u) + await expect(createAuth(discarded)).rejects.toThrow('host-authentication-token: browser-session credential record was not created') await expect(createAuth(new RecordCredentials(), Number.MAX_SAFE_INTEGER)) - .rejects.toThrow(/safe timestamp range/u) + .rejects.toThrow('host-authentication-token: cookieMaxAgeDays exceeds the safe timestamp range') }) }) diff --git a/packages/host/authentication-token/tests/browser-credentials.ts b/packages/host/authentication-token/tests/browser-credentials.ts new file mode 100644 index 0000000000..cf59f24955 --- /dev/null +++ b/packages/host/authentication-token/tests/browser-credentials.ts @@ -0,0 +1,44 @@ +/** Mutable credential records used by the token implementation tests. */ +import { CredentialProvider, type CredentialRecord } from '@deepseek-ai/dsh-credentials' +import { Context } from '@deepseek-ai/cordis' +import { onTestFinished } from 'vitest' + +export class RecordCredentials extends CredentialProvider { + constructor() { + const ctx = new Context() + super(ctx) + onTestFinished(() => ctx.fiber.dispose()) + } + + override resolve(): never { throw new Error('Reference resolution is outside this fixture') } + override describe(): never { throw new Error('Reference description is outside this fixture') } + override set(): never { throw new Error('Reference writes are outside this fixture') } + override unset(): never { throw new Error('Reference removal is outside this fixture') } + override describeRecord(): never { throw new Error('Record description is outside this fixture') } + override listRecords(): never { throw new Error('Record enumeration is outside this fixture') } + record: CredentialRecord | undefined + discardWrites = false + reads = 0 + modifies = 0 + + override readRecord(): Promise { + this.reads += 1 + return Promise.resolve(this.record) + } + + override async modifyRecord( + _key: unknown, + mutate: (current: CredentialRecord | undefined) => Promise, + ): Promise { + this.modifies += 1 + const next = await mutate(this.record) + if (this.discardWrites) return undefined + if (next !== undefined) this.record = next + return this.record + } + + override deleteRecord(): Promise { + this.record = undefined + return Promise.resolve() + } +} diff --git a/packages/host/authentication-token/tests/loader.host.spec.ts b/packages/host/authentication-token/tests/loader.host.spec.ts new file mode 100644 index 0000000000..ab21675040 --- /dev/null +++ b/packages/host/authentication-token/tests/loader.host.spec.ts @@ -0,0 +1,119 @@ +/** Real Loader composition exercises Token as an independent authentication plugin. */ +import { request as httpRequest } from 'node:http' +import { once } from 'node:events' +import type { Duplex } from 'node:stream' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context } from '@deepseek-ai/cordis' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import Include from '@deepseek-ai/cordis-plugin-include' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import LocalCredentials from '@deepseek-ai/dsh-credentials-local' +import WebServer from '@deepseek-ai/dsh-host-webserver' +import { expect, it, onTestFinished } from 'vitest' +import * as Token from '../src/index.ts' +import { BrowserAuth } from '../src/browser-auth.ts' + +it('serves token exchanges through WebServer and keeps token-owned Peers outside Connection defaults', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-token-plugin-')) + const ctx = new Context() + onTestFinished(async () => { + await ctx.fiber.dispose() + if (!isAbsolute(root) || dirname(root) !== resolve(tmpdir()) || !basename(root).startsWith('dsh-token-plugin-')) { + throw new Error(`refusing unexpected fixture cleanup path: ${root}`) + } + await rm(root, { recursive: true, force: true }) + }) + const path = join(root, 'cordis.yml') + await writeFile(path, [ + { name: 'cordis:credentials', config: { path: join(root, '.credentials.yaml'), watch: false } }, + { name: 'cordis:webserver', config: { host: '127.0.0.1', port: 0 } }, + { name: 'cordis:connection' }, + { id: 'token', name: 'cordis:token' }, + ].map(row => `- ${JSON.stringify(row)}`).join('\n') + '\n') + ctx.baseUrl = pathToFileURL(root).href + '/' + await ctx.plugin(Loader) + Object.assign(ctx.loader.builtins, { + include: Include, credentials: LocalCredentials, webserver: WebServer, connection: Connection, token: Token, + }) + await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(path).href } }) + await ctx.loader.await() + const origin = `http://127.0.0.1:${ctx.webServer.port}` + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + const login = new URL(auth.authenticatedUrl(origin)) + expect(login.searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/) + const exchanged = await fetch(login, { redirect: 'manual' }) + expect(exchanged.status).toBe(303) + expect(exchanged.headers.get('location')).toBe('./') + const cookie = exchanged.headers.get('set-cookie')?.split(';', 1)[0] + expect(cookie).toBeDefined() + const headers = { host: new URL(origin).host, cookie } + const admission = ctx.connection.authentication.authenticate({ headers }) + if ('rejection' in admission) throw new Error('token Cookie was rejected') + expect(admission.peer).not.toBe(ctx.connection.browserPeer) + expect(ctx.connection.authentication.authenticate({ headers })).toEqual(admission) + + const apiUrl = new URL(auth.authenticatedUrl(new URL('/connect', login).href)) + for (const source of [{ host: 'untrusted.example' }, { origin: 'http://untrusted.example' }, { 'sec-fetch-site': 'cross-site' }]) { + const refused = await new Promise<{ status: number | undefined; cookie: string[] | undefined }>((resolve, reject) => { + const request = httpRequest(apiUrl, { headers: source }, (response) => { + response.resume() + response.once('end', () => { resolve({ status: response.statusCode, cookie: response.headers['set-cookie'] }) }) + }) + request.once('error', reject) + request.end() + }) + expect(refused.status).toBe(403) + expect(refused.cookie).toBeUndefined() + } + const connected = await fetch(apiUrl, { redirect: 'manual' }) + expect(connected.status).toBe(302) + const apiCookie = connected.headers.get('set-cookie')?.split(';', 1)[0] + const apiHeaders = { host: new URL(origin).host, cookie: apiCookie } + const api = ctx.connection.admit({ headers: apiHeaders }) + if ('rejection' in api) throw new Error('API Cookie was rejected') + expect(api.peer).not.toBe(admission.peer) + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/page.html', auth: 'required', + resource: async (_request, peer) => Response.json({ id: peer?.id }), + })) + const page = await fetch(new URL('/page.html', login), { headers: { cookie: apiCookie! } }) + expect(page.status).toBe(200) + expect(await page.json()).toEqual({ id: api.peer.id }) + ctx.effect(() => ctx.webServer.registerUpgrade({ + path: '/api/remote.mux', + handler(_request, socket) { + socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: fixture\r\n\r\n') + }, + })) + const socket = await new Promise((resolve, reject) => { + const request = httpRequest(new URL('/api/remote.mux', origin), { + headers: { cookie: apiCookie!, connection: 'Upgrade', upgrade: 'fixture' }, + }) + request.once('upgrade', (_response, socket) => { resolve(socket) }) + request.once('error', reject) + request.end() + }) + socket.resume() + const closed = once(socket, 'close') + onTestFinished(async () => { socket.destroy(); await closed }) + await api.peer.dispose() + await closed + expect((await fetch(new URL('/page.html', login), { headers: { cookie: apiCookie! } })).status).toBe(401) + expect(ctx.connection.admit({ headers: apiHeaders })).toEqual({ rejection: 401 }) + + const originalToken = login.searchParams.get('token') + const token = [...ctx.loader.entries()].find(entry => entry.options.id === 'token') + if (token?.fiber === undefined) throw new Error('token provider did not activate') + await token.fiber.dispose() + expect(admission.peer.signal.aborted).toBe(true) + expect(ctx.connection.admit({ headers })).toEqual({ rejection: 401 }) + await ctx.plugin(Token, { cookieMaxAgeDays: 30 }).await() + const reloaded = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + const restarted = new URL(reloaded.authenticatedUrl(origin)) + expect(restarted.searchParams.get('token')).toBe(originalToken) + const resumed = ctx.connection.authentication.authenticate({ headers }) + if ('rejection' in resumed) throw new Error('existing Cookie did not survive provider reload') + expect(resumed.peer).not.toBe(admission.peer) +}) diff --git a/packages/host/authentication-token/tests/plugin.host.spec.ts b/packages/host/authentication-token/tests/plugin.host.spec.ts new file mode 100644 index 0000000000..14d5f85f28 --- /dev/null +++ b/packages/host/authentication-token/tests/plugin.host.spec.ts @@ -0,0 +1,229 @@ +/** Token plugin owns its HTTP exchange and returns existing Connection Peers. */ +import { Context } from '@deepseek-ai/cordis' +import { afterEach, expect, it, vi } from 'vitest' +import { ConnectionAuthentication, type AuthenticationProvider, type HostConnectionHandle, type PeerScope } from '@deepseek-ai/dsh-client-connection' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { once } from 'node:events' +import { PassThrough } from 'node:stream' +import type { WebEntryUrl, WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver' +import * as Token from '../src/index.ts' +import { RecordCredentials } from './browser-credentials.ts' +import { BrowserAuth } from '../src/browser-auth.ts' + +const roots: Context[] = [] +afterEach(async () => { for (const ctx of roots.splice(0)) await ctx.fiber.dispose() }) + +async function mounted(secure = false, before?: (ctx: Context) => void) { + const ctx = new Context(); roots.push(ctx) + const providers: AuthenticationProvider[] = [] + const routes: WebRoute[] = [] + let sequence = 0 + const createPeer = vi.fn((options) => { + const signal = new AbortController() + const peer = { + id: `peer-${++sequence}`, principal: options.principal, interactions: options.interactions ?? 'answer', ctx, + signal: signal.signal, dispose: async () => { signal.abort() }, + } as PeerScope + return peer + }) + const authentication = new ConnectionAuthentication(ctx) + const connection: HostConnectionHandle = { + authentication, + browserPeer: { principal: { kind: 'owner' }, interactions: 'answer', ctx, signal: new AbortController().signal, + id: 'compat-peer', dispose: async () => {} } as PeerScope, + allowsRemoteAuthorities: false, + rpc: { + handle() { throw new Error('RPC registration is outside this fixture') }, + intercept() { throw new Error('RPC interception is outside this fixture') }, + }, + fetch: { register() { throw new Error('Fetch routes are outside this fixture') } }, + createSharedFetchHandler() { throw new Error('Fetch dispatch is outside this fixture') }, + admit() { throw new Error('Combined admission is outside this fixture') }, + createPeer, + } + ctx.provide('credentials', new RecordCredentials()) + ctx.provide('connection', connection) + ctx.provide('webServer', { + protocol: secure ? 'https:' : 'http:', + register(route: WebRoute) { routes.push(route); return () => { routes.splice(routes.indexOf(route), 1) } }, + } as WebServer) + before?.(ctx) + const fiber = ctx.plugin({ + inject: Token.inject, + async apply(scope: Context) { + authentication.register = provider => scope.effect(() => { + providers.push(provider) + return () => { providers.splice(providers.indexOf(provider), 1) } + }) + await Token.apply(scope, { cookieMaxAgeDays: 30 }) + }, + }) + await fiber.await() + const auth = await BrowserAuth.create(ctx.root, ctx.credentials, 30) + return { ctx, fiber, providers, routes, createPeer, auth } +} +function response() { + const state: { status?: number; headers?: Readonly> | undefined; body?: string | undefined } = {} + const res = { + destroyed: false, + writeHead(status: number, headers?: Readonly>) { state.status = status; state.headers = headers }, + end(body?: string) { state.body = body }, + } as ServerResponse + return { res, state } +} +function request(url: string, method = 'GET'): IncomingMessage { + return { url, method, headers: { host: 'localhost:3080' }, socket: { destroyed: false } } as IncomingMessage +} + +it('keeps login URL construction internal and registers only the standard plugin exports', async () => { + expect(Object.keys(Token).sort()).toEqual(['Config', 'apply', 'inject', 'name']) + const { providers, createPeer, auth } = await mounted() + const url = new URL(auth.authenticatedUrl('http://localhost:3080/mount/?other=1')) + expect(url.pathname).toBe('/mount/') + expect(url.searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/) + expect(url.searchParams.get('other')).toBe('1') + expect(providers).toHaveLength(1) + expect(providers[0]!.authenticate({ headers: { host: 'localhost:3080' } })).toBeUndefined() + expect(createPeer).toHaveBeenCalledExactlyOnceWith({ principal: { kind: 'owner' } }) +}) + +it('exchanges a root token, passes other routes on, and keeps browser authentication shared', async () => { + const { ctx, providers, createPeer, auth } = await mounted() + const url = new URL(auth.authenticatedUrl('http://localhost:3080/')) + const reply = response(); const next = vi.fn(async () => {}) + await ctx.waterfall('webserver/request', request(url.pathname + url.search), reply.res, next) + expect(reply.state.status).toBe(303) + expect(next).not.toHaveBeenCalled() + const cookie = reply.state.headers?.['set-cookie']?.split(';', 1)[0] + expect(cookie).toBeDefined() + const facts = { headers: { host: 'localhost:3080', cookie } } + const peer = providers[0]!.authenticate(facts) + expect(peer).toBe(createPeer.mock.results[0]!.value) + expect(providers[0]!.authenticate(facts)).toBe(peer) + await ctx.waterfall('webserver/request', request('/product.html?token=other'), response().res, next) + expect(next).toHaveBeenCalledTimes(1) + await ctx.waterfall('webserver/request', request('/'), response().res, next) + expect(next).toHaveBeenCalledTimes(2) + const noTarget = request('/') + noTarget.url = undefined + await ctx.waterfall('webserver/request', noTarget, response().res, next) + expect(next).toHaveBeenCalledTimes(3) + const disconnected = request(url.pathname + url.search) + Object.assign(disconnected.socket, { destroyed: true }) + const dropped = response() + await ctx.waterfall('webserver/request', disconnected, dropped.res, next) + expect(dropped.state.status).toBeUndefined() +}) + +it('delegates synthetic Worker requests without a native socket', async () => { + const { ctx, routes, auth } = await mounted() + const synthetic = request('/plugins/??modules/client.js') + Reflect.deleteProperty(synthetic, 'socket') + const next = vi.fn(async () => {}) + await ctx.waterfall('webserver/request', synthetic, response().res, next) + expect(next).toHaveBeenCalledOnce() + + const url = new URL(auth.authenticatedUrl('http://localhost:3080/connect')) + const connect = request(url.pathname + url.search) + Reflect.deleteProperty(connect, 'socket') + const reply = response() + await routes[0]!.handler(connect, reply.res) + expect(reply.state.status).toBe(302) +}) + +it('creates socket-owned API Peers usable by authenticated routes', async () => { + const { providers, routes, createPeer, auth } = await mounted() + const url = new URL(auth.authenticatedUrl('http://localhost:3080/connect')) + const reply = response() + await routes[0]!.handler(request(url.pathname + url.search), reply.res) + expect(reply.state.status).toBe(302) + expect(createPeer).toHaveBeenLastCalledWith({ principal: { kind: 'owner' }, interactions: 'none' }) + const cookie = reply.state.headers?.['set-cookie']?.split(';', 1)[0] + const facts = { headers: { host: 'localhost:3080', cookie } } + expect(routes[0]!.auth).toBe('anonymous') + expect(providers[0]!.authenticate(facts)).toBe(createPeer.mock.results[1]!.value) + const before = createPeer.mock.calls.length + const disconnected = request(url.pathname + url.search) + Object.assign(disconnected.socket, { destroyed: true }) + await routes[0]!.handler(disconnected, response().res) + expect(createPeer).toHaveBeenCalledTimes(before) +}) + +it('does not claim an API Peer when an upgrade has no request target', async () => { + const { ctx, providers, routes, auth } = await mounted() + const url = new URL(auth.authenticatedUrl('http://localhost:3080/connect')) + const reply = response() + await routes[0]!.handler(request(url.pathname + url.search), reply.res) + const cookie = reply.state.headers?.['set-cookie']?.split(';', 1)[0] + const facts = { headers: { host: 'localhost:3080', cookie } } + const peer = providers[0]!.authenticate(facts) + if (peer === undefined) throw new Error('fixture API Cookie was refused') + const incoming = request('/') + incoming.url = undefined + const socket = new PassThrough() + const closed = once(socket, 'close') + const next = vi.fn(async () => {}) + try { + await ctx.waterfall('webserver/upgrade', incoming, socket, Buffer.alloc(0), peer, next) + expect(next).toHaveBeenCalledOnce() + } finally { + socket.destroy() + await closed + } + expect(peer.signal.aborted).toBe(false) + expect(providers[0]!.authenticate(facts)).toBe(peer) +}) + +it('delegates a queued root request after its token middleware has unloaded', async () => { + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const { ctx, fiber, auth } = await mounted(false, (owner) => { + owner.on('webserver/request', async (_request, _response, next) => { + entered.resolve(undefined) + await release.promise + await next() + }) + }) + const url = new URL(auth.authenticatedUrl('http://localhost:3080/')) + const reply = response() + const next = vi.fn(async () => {}) + const pending = ctx.waterfall('webserver/request', request(url.pathname + url.search), reply.res, next) + await entered.promise + await fiber.dispose() + release.resolve(undefined) + await pending + expect(reply.state.headers?.['set-cookie']).toBeUndefined() + expect(next).toHaveBeenCalledOnce() +}) + +it('refuses invalid API interaction declarations without creating a Peer', async () => { + const { routes, createPeer, auth } = await mounted() + const url = new URL(auth.authenticatedUrl('http://localhost:3080/connect?interactions=invalid')) + const reply = response() + await routes[0]!.handler(request(url.pathname + url.search), reply.res) + expect(reply.state.status).toBe(400) + expect(createPeer).toHaveBeenCalledTimes(1) +}) + +it('removes all entry registrations on unload', async () => { + const { fiber, providers, routes } = await mounted() + const captured = routes[0]! + await fiber.dispose() + const stale = response() + await captured.handler(request('/connect?token=old'), stale.res) + expect(stale.state.status).toBe(401) + expect(providers).toHaveLength(0) + expect(routes).toHaveLength(0) +}) + + +it('contributes its complete login URL only while the provider is mounted', async () => { + const { ctx, fiber, auth } = await mounted() + const entries: WebEntryUrl[] = [] + ctx.emit('webserver/entry-url', 'https://public.test/ui/', entries) + expect(entries).toEqual([{ label: 'dsh web', url: auth.authenticatedUrl('https://public.test/ui/'), open: true }]) + await fiber.dispose() + const after: WebEntryUrl[] = [] + ctx.emit('webserver/entry-url', 'https://public.test/ui/', after) + expect(after).toEqual([]) +}) diff --git a/packages/host/authentication-token/tsconfig.json b/packages/host/authentication-token/tsconfig.json new file mode 100644 index 0000000000..f5ba9984bb --- /dev/null +++ b/packages/host/authentication-token/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { "rootDir": "src", "outDir": "lib/types" }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../client/connection/tsconfig.host.json" }, + { "path": "../../credentials/credentials" }, + { "path": "../webserver" }, + { "path": "../../typert/protocol" } + ] +} diff --git a/packages/host/frontend-static/README.i18n.yaml b/packages/host/frontend-static/README.i18n.yaml index eff4799bf6..24d5437209 100644 --- a/packages/host/frontend-static/README.i18n.yaml +++ b/packages/host/frontend-static/README.i18n.yaml @@ -9,8 +9,8 @@ en: a7cd4201b26f235e zh: 466d0b60950685b4 /deepseek-ai-dsh-host-frontend-static/summary: - en: 788005d86b2cf415 - zh: 5d3073e3e5144084 + en: ee3d90175c3b3949 + zh: 8934aaec3365a1d3 /deepseek-ai-dsh-host-frontend-static/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb @@ -21,8 +21,8 @@ en: c58118ab4aba9bac zh: 334fcd54edcae152 /deepseek-ai-dsh-host-frontend-static/use-this-package/what-the-server-enforces: - en: 7763bc4e95a22f20 - zh: f609acbe0cbcfae9 + en: d74821ff58fbbbe4 + zh: d2e627610e6f2fa2 /deepseek-ai-dsh-host-frontend-static/use-this-package/observable-failures: en: 7b6cca6ed823f515 zh: 30b5a5c594e8f1b8 @@ -30,8 +30,8 @@ en: 42b15ac6321706aa zh: 4ed0861911abaf5d /deepseek-ai-dsh-host-frontend-static/understand-the-implementation/design-concept: - en: 6b8f640e949cd08c - zh: 5da78a82c6fb3efb + en: 3a2158f7322888bd + zh: 88f4ab6339ff9987 /deepseek-ai-dsh-host-frontend-static/understand-the-implementation/the-traversal-fence: en: 0ca9ccfdf4101cf1 zh: 5a01e561397afcb1 diff --git a/packages/host/frontend-static/README.md b/packages/host/frontend-static/README.md index 5fd118b5c3..9146825b32 100644 --- a/packages/host/frontend-static/README.md +++ b/packages/host/frontend-static/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Serve the built Web shell to browsers from its configured distribution directory. The root and configured index path render the bootstrapped index; existing assets are served directly, while missing or non-file paths return 404, traversal returns 403, and unsupported methods return 405. Index access requires a valid process token or browser cookie, but static assets remain public. Only one instance can handle unmatched routes at a time; a second activation fails, and unloading the active instance makes unmatched requests return 404. +Serve the built Web shell from its configured distribution directory. Root and configured-index entries require an authenticated Peer and render its startup data; other assets need no credentials but still pass active Connection source checks. Missing or non-file paths return 404, traversal returns 403, and admitted requests with unsupported methods return 405. Only one instance can own unmatched requests; a second activation fails, and unloading it leaves unmatched requests at 404. ## Table of Contents @@ -39,11 +39,11 @@ Compose this plugin in a browser-facing host that serves the built Web shell: it ### What the server enforces -Requests are served from the dist root (the directory containing `distIndex`). The dist root and the configured index path render `index.html` with HTTP 200; any other existing file is served directly with its MIME type, and unknown extensions ship as `application/octet-stream`. A path that resolves outside the root is rejected with 403, so a crafted path cannot read files above the dist. An absent or non-file target inside the dist root — a missing file, a directory, or a missing configured index — returns an empty 404. Non-GET/HEAD requests without a matching named route are answered 405. The fallback is a webserver resource. Every successful index response is rendered through the webserver's `renderIndex` — for `connection.browserPeer`, the Peer Connection's browser authentication admits, over HTTP, and for `peer` in a `webServer.readResource(request, peer)` read, which skips browser authentication — so the boot manifest and that Peer's access snapshot reach the page on `/` and on the configured index path. +Requests are served from the dist root (the directory containing `distIndex`). The root and configured index render `index.html` with 200; other existing files use their MIME type, or `application/octet-stream` for unknown extensions. Paths outside the root return 403; missing or non-file targets return empty 404 responses. After admission, non-GET/HEAD requests return 405. The fallback resource renders each index through `webServer.renderIndex` with the Peer WebServer admitted, or the explicit Peer supplied to trusted `webServer.readResource(request, peer)`. The boot manifest and that Peer's access snapshot reach both index entry paths. The served HTML carries one document base, ``, ahead of every injected resource row, so it freezes the entry directory the page was loaded from: the shell's own app-directory-relative references and the Host's plugin-resource rows both resolve under the mount that served the page. The same index therefore serves the origin root and whatever mount a prefix-stripping proxy owns; this plugin renders it only for the dist root and the configured index path. -HTTP root and configured-index requests call `ctx.connection.authorizeIndex` before reading HTML. A valid process token receives a 303 redirect plus the persistent browser cookie; an existing valid cookie serves the index; every other index request receives the Connection-owned 401 response. Non-index files remain public static assets. Connection owns the token, cookie, expiry, and signing-record semantics. +The fallback's synchronous `auth` selector requires `required` for root and configured-index requests and declares other files `anonymous`. WebServer centralizes admission through Connection before file serving; anonymous assets skip credential verification, not Connection's source policy. The resource receives the admitted Peer directly and captures it for index rendering without another authentication call. Token middleware handles the root Cookie exchange before routing. After reading index bytes, rendering checks that both request and Peer remain live. Browsers revalidate every served file except the index. Such a response carries `cache-control: no-cache` and a weak ETag built from a SHA-1 of the file's bytes, so a file whose content changes gets a new ETag even when its name stays the same; a request whose `If-None-Match` equals the current ETag receives an empty 304. The rendered index carries no cache headers. @@ -61,7 +61,7 @@ Traversal returns 403 rather than an error page. An absent or non-file target in ### Design concept -The package is one function plugin around `serveStatic`, which maps a Fetch `Request` to a `Response`: `apply` resolves the dist root from `distIndex` and registers a fallback resource under an effect scope. For each request the resource passes `serveStatic` an `authorizeIndex` closure, which runs `ctx.connection.authorizeIndex` only when no Peer came with the request, and a `renderIndex` closure that runs `ctx.webServer.renderIndex` over the raw `index.html` for that Peer or the browser Peer and splices the document base in after the opening head tag (after the raw taps, so it precedes their markup too). The seat is single-owner by the webserver's contract — a second registration throws — and effect-scoped, so disposing the fiber releases the seat. +The function plugin wraps `serveStatic`, which maps a Fetch `Request` to a `Response`. Its fallback declares route auth and consumes the Peer WebServer supplies; in-process reads use the caller's explicit Peer. The renderer runs index transforms and inserts the document base before resource references. The plugin scope owns the fallback registration and releases its single-owner seat on disposal. ### The traversal fence diff --git a/packages/host/frontend-static/README.zh.md b/packages/host/frontend-static/README.zh.md index 2839f07a93..87aad11040 100644 --- a/packages/host/frontend-static/README.zh.md +++ b/packages/host/frontend-static/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -从配置的发布目录向浏览器提供已构建的 Web 壳。根路径与配置的 index 路径渲染包含启动信息的 index;已有资产直接提供,而缺失或非文件路径返回 404、路径遍历返回 403、不支持的方法返回 405。访问 index 需要有效的进程 token 或浏览器 cookie,但静态资产仍可公开访问。同一时间只能有一个实例处理未匹配的路由;第二个实例启动失败,卸载活动实例后,未匹配的请求返回 404。 +从配置的发布目录提供已构建的 Web 壳。根路径与配置的 index 入口要求认证 Peer,并渲染其启动数据;其他资源无需凭据,但仍经过活动 Connection 的来源检查。缺失或非文件路径返回404、遍历返回403,已准入但方法不受支持的请求返回405。同一时间只能有一个实例拥有未匹配请求;第二次激活失败,卸载后未匹配请求返回404。 ## 目录 @@ -39,11 +39,11 @@ kind: "package-reference" ### 服务器实施的约束 -请求从 dist 根目录(包含 `distIndex` 的目录)提供。dist 根目录与配置的 index 路径以 HTTP 200 渲染 `index.html`;任何其他已有文件按自身 MIME 类型直接提供,未知扩展名按 `application/octet-stream` 提供。解析到根目录之外的路径以 403 拒绝,因此精心构造的路径无法读取 dist 之上的文件。dist 根目录内不存在或不是文件的目标——文件缺失、目录或配置的 index 缺失——返回空 404。没有匹配具名路由的非 GET/HEAD 请求返回 405。回退是一个 webserver resource。每个成功的 index 响应都经 webserver 的 `renderIndex` 渲染——经 HTTP 时为 `connection.browserPeer`(Connection 浏览器认证所准入的 Peer),在 `webServer.readResource(request, peer)` 读取中为 `peer` 且跳过浏览器认证——因此启动 manifest(元数据清单)与该 Peer 的访问快照会通过 `/` 与配置的 index 路径送达页面。 +请求从 dist 根目录(包含 `distIndex` 的目录)提供。根路径与配置 index 以200渲染 `index.html`;其他已有文件使用其 MIME 类型,未知扩展名使用 `application/octet-stream`。根目录外路径返回403,缺失或非文件目标返回空404。准入后,非 GET/HEAD 请求返回405。回退 resource 通过 `webServer.renderIndex` 渲染各 index,使用 WebServer 准入的 Peer,或可信 `webServer.readResource(request, peer)` 显式传入的 Peer。启动 manifest(元数据清单)与该 Peer 的访问快照会送达两个 index 入口。 所服务的 HTML 携带唯一的文档 base ``,位于每一条注入资源行之前,因此它冻结页面加载时所处的入口目录:shell 自身的应用目录相对引用与宿主的插件资源行都在服务该页面的挂载下解析。同一份 index 因而既服务源站根目录,也服务剥离前缀的代理所拥有的任一挂载;本插件只为 dist 根目录与配置的 index 路径渲染它。 -对根路径与配置 index 的 HTTP 请求会在读取 HTML 前调用 `ctx.connection.authorizeIndex`。有效进程 token 会得到 303 重定向与持久浏览器 cookie;已有有效 cookie 时直接提供 index;其他 index 请求得到 Connection 所有的 401 响应。非 index 文件仍是公开静态资源。Token、cookie、过期时间与签名记录语义都归 Connection 所有。 +回退的同步 `auth` 选择器对根路径与配置 index 请求要求 `required`,其余文件声明 `anonymous`。WebServer 在文件服务前通过 Connection 集中准入;匿名资源免凭据验证,但仍执行 Connection 来源策略。resource 直接接收准入 Peer 并供 index 渲染闭包使用,不重复认证。Token 中间件在路由前处理根路径 Cookie 交换。读取 index 内容后,渲染检查请求与 Peer 均仍存活。 除 index 外,所有提供的文件都由浏览器重新验证。这类响应携带 `cache-control: no-cache` 和由文件内容 SHA-1 生成的弱 ETag,因此文件内容变化后即使名字不变也会得到新的 ETag;`If-None-Match` 等于当前 ETag 的请求得到空的 304。渲染出的 index 不带缓存头。 @@ -61,7 +61,7 @@ kind: "package-reference" ### 设计理念 -本包是围绕 `serveStatic` 的一个函数插件,`serveStatic` 把 Fetch `Request` 映射为 `Response`:`apply` 从 `distIndex` 解析出 dist 根目录,并在 effect 作用域下注册回退 resource。每个请求中,resource 交给 `serveStatic` 一个 `authorizeIndex` 闭包——只在请求没有携带 Peer 时运行 `ctx.connection.authorizeIndex`——以及一个 `renderIndex` 闭包:它为该 Peer 或浏览器 Peer 对原始 `index.html` 运行 `ctx.webServer.renderIndex`,并把文档 base 拼接在起始 head 标签之后(在原始转换之后执行,因此也先于其标记)。按 webserver 的约定,席位只有单一所有者——第二次注册会抛错——且受 effect 作用域约束,因此 dispose fiber 即释放席位。 +函数插件包装 `serveStatic`,将 Fetch `Request` 映射为 `Response`。回退声明路由 auth,使用 WebServer 提供的 Peer;进程内读取使用调用方的显式 Peer。renderer 执行 index 转换,并在资源引用前插入文档 base。插件作用域拥有回退注册,并在 dispose 时释放唯一席位。 ### 遍历栅栏 diff --git a/packages/host/frontend-static/package.json b/packages/host/frontend-static/package.json index 0370ab1bb8..000a5bfda1 100644 --- a/packages/host/frontend-static/package.json +++ b/packages/host/frontend-static/package.json @@ -40,6 +40,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { + "@deepseek-ai/dsh-host-authentication-token": "workspace:*", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", diff --git a/packages/host/frontend-static/src/index.ts b/packages/host/frontend-static/src/index.ts index 609d2062dc..5415ae587e 100644 --- a/packages/host/frontend-static/src/index.ts +++ b/packages/host/frontend-static/src/index.ts @@ -5,7 +5,7 @@ * and configured index path; missing paths return 404, traversal outside the * dist root is 403, unknown extensions ship as octet-stream, and non-GET/HEAD * is 405. An HTTP index request first passes Connection's browser - * authentication and renders for the browser Peer; an in-process read renders + * authentication and renders for its admitted Peer; an in-process read renders * for the Peer its caller admitted. Both renders go through the webserver's * index render (structured injection rows, then raw taps). Non-index assets * stay public; every file other than the index carries a weak ETag with @@ -21,7 +21,7 @@ import { readFile } from 'node:fs/promises' import { dirname, extname, join, normalize, resolve, sep } from 'node:path' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type {} from '@deepseek-ai/dsh-client-connection' +import type { PeerScope } from '@deepseek-ai/dsh-client-connection' import type {} from '@deepseek-ai/dsh-host-webserver' /** Stable Cordis plugin name. */ @@ -81,10 +81,8 @@ function bytesBody(bytes: Uint8Array): ReadableStream { * @param request - the request; only its method and URL path are read. * @param distRoot - absolute dist root directory (resolved by the caller). * @param distIndex - absolute path of index.html inside distRoot. - * @param authorizeIndex - answers an index request before its bytes are read: - * the response to send instead of the index, or undefined to serve it. - * @param renderIndex - turns the raw index.html body into the served document - * for the dist root and configured index path. + * @param renderIndex - present for index requests to turn the raw index.html + * into the served document; omitted for ordinary static files. * @returns the dist response; a HEAD response carries the GET status and * headers without a body. A file other than the index carries * `cache-control: no-cache` and a weak ETag from a SHA-1 of its bytes, and a @@ -92,8 +90,7 @@ function bytesBody(bytes: Uint8Array): ReadableStream { */ async function serveStatic( request: Request, distRoot: string, distIndex: string, - authorizeIndex: () => Response | undefined, - renderIndex: (html: string) => string, + renderIndex?: (html: string) => string, ): Promise { const target = resolve(normalize(join(distRoot, decodeURIComponent(new URL(request.url).pathname)))) // Traversal rejection: the target must be distRoot itself (`/`) or stay under @@ -103,10 +100,10 @@ async function serveStatic( let body: string | Uint8Array let headers: Record try { - if (target === distRoot || target === distIndex) { - const refusal = authorizeIndex() - if (refusal !== undefined) return refusal - body = renderIndex(await readFile(distIndex, 'utf8')) + if (renderIndex !== undefined) { + const html = await readFile(distIndex, 'utf8') + request.signal.throwIfAborted() + body = renderIndex(html) headers = { 'content-type': HTML_MIME } } else { body = await readFile(target) @@ -133,35 +130,24 @@ async function serveStatic( export function apply(ctx: Context, config: Config): void { const distIndex = config.distIndex const distRoot = dirname(distIndex) - // Connection's browser authentication writes the token exchange's 303 or - // the 401 through a writeHead/end response; capture it as a Fetch response. - // The answer stays a 401 unless Connection writes another one. - const authorizeIndex = (request: Request): Response | undefined => { - let status = 401 - let headers = new Headers() - let body: string | undefined - const admitted = ctx.connection.authorizeIndex(request, { - writeHead(nextStatus, nextHeaders) { - status = nextStatus - headers = new Headers(nextHeaders) - }, - end(text) { body = text }, - }) - return admitted ? undefined : new Response(body, { status, headers }) - } ctx.effect(() => ctx.webServer.registerFallback({ - resource: (request, peer) => serveStatic( - request, - distRoot, - distIndex, - // A read with a Peer was admitted by its caller; an HTTP request carries - // none and passes Connection's browser authentication instead. - () => peer === undefined ? authorizeIndex(request) : undefined, - // The browser authentication admits the owner's shared browser Peer. The - // base goes in after all index transforms, so it precedes every resource - // reference they insert. - html => ctx.webServer.renderIndex(html, peer ?? ctx.connection.browserPeer) - .replace(/]*)?>/i, open => `${open}`), - ), + auth: (request) => { + const target = resolve(normalize(join(distRoot, decodeURIComponent(request.url.pathname)))) + return target === distRoot || target === distIndex ? 'required' : 'anonymous' + }, + resource: (request, peer) => { + request.signal.throwIfAborted() + const target = resolve(normalize(join(distRoot, decodeURIComponent(new URL(request.url).pathname)))) + if (target !== distRoot && target !== distIndex) return serveStatic(request, distRoot, distIndex) + // WebServer admits every index request before invoking this resource. + const pagePeer = peer as PeerScope + const render = (html: string): string => { + request.signal.throwIfAborted() + pagePeer.signal.throwIfAborted() + return ctx.webServer.renderIndex(html, pagePeer) + .replace(/]*)?>/i, open => `${open}`) + } + return serveStatic(request, distRoot, distIndex, render) + }, }), 'frontend-static: fallback seat') } diff --git a/packages/host/frontend-static/tests/frontend-static.spec.ts b/packages/host/frontend-static/tests/frontend-static.spec.ts index 0c7ea9c2f3..3f09e701eb 100644 --- a/packages/host/frontend-static/tests/frontend-static.spec.ts +++ b/packages/host/frontend-static/tests/frontend-static.spec.ts @@ -10,19 +10,43 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import * as Connection from '@deepseek-ai/dsh-client-connection' +import * as Token from '@deepseek-ai/dsh-host-authentication-token' +import { BrowserAuth } from '@deepseek-ai/dsh-host-authentication-token/src/browser-auth.ts' import LocalCredentials from '@deepseek-ai/dsh-credentials-local' import HttpServer from '@deepseek-ai/dsh-host-webserver' import * as FrontendStatic from '../src/index.ts' +const heldIndex = vi.hoisted(() => ({ + path: undefined as string | undefined, + entered: undefined as (() => void) | undefined, + release: undefined as Promise | undefined, +})) +vi.mock('node:fs/promises', async (importOriginal) => { + const original = await importOriginal() + return { + ...original, + readFile: async (...args: Parameters) => { + if (args[0] === heldIndex.path) { + heldIndex.entered?.() + await heldIndex.release + } + return original.readFile(...args) + }, + } +}) + let root: string | undefined let context: Context | undefined afterEach(async () => { + heldIndex.path = undefined + heldIndex.entered = undefined + heldIndex.release = undefined await context?.fiber.dispose() context = undefined if (root !== undefined) await rm(root, { recursive: true, force: true }) @@ -53,6 +77,7 @@ async function loadComposition(): Promise { " host: '127.0.0.1'", ' port: 0', "- name: '@deepseek-ai/dsh-client-connection'", + "- name: '@deepseek-ai/dsh-host-authentication-token'", '- id: frontend', " name: '@deepseek-ai/dsh-host-frontend-static'", ' config:', @@ -68,6 +93,7 @@ async function loadComposition(): Promise { ['@deepseek-ai/dsh-credentials-local', LocalCredentials], ['@deepseek-ai/dsh-host-webserver', HttpServer], ['@deepseek-ai/dsh-client-connection', Connection], + ['@deepseek-ai/dsh-host-authentication-token', Token], ['@deepseek-ai/dsh-host-frontend-static', FrontendStatic], ]) context.loader.internal = { @@ -109,7 +135,8 @@ describe('real Loader composition', () => { expect(unloaded).toEqual([]) const server = loaded.webServer const port = server.port - const launchUrl = loaded.connection.authenticatedUrl(`http://127.0.0.1:${String(port)}`) + const auth = await BrowserAuth.create(loaded.root, loaded.credentials, 30) + const launchUrl = new URL(auth.authenticatedUrl(`http://127.0.0.1:${String(port)}`)) const exchange = await fetch(launchUrl, { redirect: 'manual' }) expect(exchange.status).toBe(303) expect(exchange.headers.get('location')).toBe('./') @@ -124,8 +151,8 @@ describe('real Loader composition', () => { expect(await request(port, '/')).toMatchObject({ status: 401, - type: 'text/plain; charset=utf-8', - body: 'dsh web authentication required; reopen the URL printed by dsh web.\n', + type: null, + body: 'unauthorized', }) // Real assets with their MIME types; a live rebuild is served on the next read. @@ -157,7 +184,8 @@ describe('real Loader composition', () => { renderedFor.push(peer) rows.push({ kind: 'script-preload', src: 'plugins/boot.js' }) }) - for (const path of ['/', '/index.html', '/?view=test']) { + expect((await request(port, '/index.html?token=ordinary-query')).status).toBe(401) + for (const path of ['/', '/index.html', '/?view=test', '/index.html?token=ordinary-query']) { const got = await request(port, path, authenticated()) expect(got.status).toBe(200) expect(got.type).toBe('text/html; charset=utf-8') @@ -171,8 +199,11 @@ describe('real Loader composition', () => { expect(base).toBeLessThan(got.body.indexOf('')) expect(base).toBeLessThan(got.body.indexOf('')) } - // An authenticated browser renders for the owner's shared browser Peer. - expect(renderedFor).toEqual([loaded.connection.browserPeer, loaded.connection.browserPeer, loaded.connection.browserPeer]) + // Default-token requests render for the Peer owned by the token provider. + const admission = loaded.connection.authentication.authenticate({ headers: { host: `127.0.0.1:${String(port)}`, cookie } }) + if ('rejection' in admission) throw new Error('token provider refused its issued Cookie') + expect(admission.peer).not.toBe(loaded.connection.browserPeer) + expect(renderedFor).toEqual([admission.peer, admission.peer, admission.peer, admission.peer]) offRows() expect(await request(port, '/', authenticated({ method: 'HEAD' }))).toEqual({ status: 200, @@ -230,10 +261,95 @@ describe('real Loader composition', () => { expect(() => server.registerFallback(() => {})).not.toThrow() }) + it('uses centralized HTTP admission while public files and in-process reads stay independent', { timeout: 60_000 }, async () => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) + let attempts = 0 + loaded.connection.authentication.register({ authenticate() { + attempts++ + return undefined + } }) + for (const path of ['/app.js', '/preview.html', '/missing.js', '/..%2f..%2foutside']) await request(loaded.webServer.port, path) + expect(attempts).toBe(0) + const inProcess = await loaded.webServer.readResource(new Request('http://reader.invalid/'), reader) + await inProcess.text() + expect(attempts).toBe(0) + expect((await request(loaded.webServer.port, '/')).status).toBe(401) + expect(attempts).toBe(1) + expect((await request(loaded.webServer.port, '/index.html', { method: 'HEAD' })).status).toBe(401) + expect(attempts).toBe(2) + }) + + it('renders each HTTP index for the Peer returned by page admission', { timeout: 60_000 }, async () => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' }, interactions: 'none' }) + expect(reader).not.toBe(loaded.connection.browserPeer) + let attempts = 0 + const unregister = loaded.connection.authentication.register({ + authenticate(input) { + attempts++ + const value = input.headers instanceof Headers ? input.headers.get('x-reader') : input.headers['x-reader'] + return value === 'external' ? reader : undefined + }, + }) + const renderedFor: Connection.PeerScope[] = [] + loaded.on('webserver/index-inject', (rows, peer) => { + renderedFor.push(peer) + rows.push({ kind: 'global', name: '__READER__', value: peer === reader }) + }) + for (const path of ['/', '/index.html']) { + const response = await request(loaded.webServer.port, path, { headers: { 'x-reader': 'external' } }) + expect(response.status).toBe(200) + expect(response.body).toContain('globalThis["__READER__"] = true') + } + expect(renderedFor).toEqual([reader, reader]) + expect(attempts).toBe(2) + await unregister() + expect((await request(loaded.webServer.port, '/', { headers: { 'x-reader': 'external' } })).status).toBe(401) + }) + + it('reports unavailable authentication without rendering the index', async () => { + const loaded = await loadComposition() + loaded.connection.authentication.register({ authenticate() { throw new Error('provider unavailable') } }) + const rendered = vi.fn() + loaded.on('webserver/index-inject', rendered) + for (const path of ['/', '/index.html']) { + expect(await request(loaded.webServer.port, path)).toMatchObject({ status: 503, body: 'authentication unavailable' }) + expect(await request(loaded.webServer.port, path, { method: 'HEAD' })).toMatchObject({ status: 503, body: '' }) + } + expect(rendered).not.toHaveBeenCalled() + }) + + it.each(['request', 'peer'] as const)('does not inject an index after its %s ends during file reading', { timeout: 60_000 }, async (ended) => { + const loaded = await loadComposition() + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) + const controller = new AbortController() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + heldIndex.path = join(root!, 'dist', 'index.html') + heldIndex.entered = () => { entered.resolve(undefined) } + heldIndex.release = release.promise + const renderedFor: Connection.PeerScope[] = [] + loaded.on('webserver/index-inject', (_rows, peer) => { renderedFor.push(peer) }) + const result = loaded.webServer.readResource(new Request('http://reader.invalid/', { signal: controller.signal }), reader) + const outcome = result.then(() => 'served', () => 'cancelled') + try { + await entered.promise + if (ended === 'request') controller.abort() + else await reader.dispose() + release.resolve(undefined) + expect(await outcome).toBe('cancelled') + expect(renderedFor).toEqual([]) + } finally { + release.resolve(undefined) + await outcome + } + }) + it('answers in-process reads for the given Peer without browser authentication', { timeout: 60_000 }, async () => { const loaded = await loadComposition() const server = loaded.webServer - const reader = { principal: { kind: 'owner' } } as Connection.PeerScope + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) const read = (path: string, init?: RequestInit) => server.readResource(new Request(`http://reader.invalid${path}`, init), reader) const renderedFor: Connection.PeerScope[] = [] loaded.on('webserver/index-inject', (rows, peer) => { @@ -283,7 +399,7 @@ describe('real Loader composition', () => { expect([revalidated.status, revalidated.headers.get('etag'), revalidated.headers.get('cache-control')]).toEqual([304, etag, 'no-cache']) expect(await revalidated.text()).toBe('') // An in-process read revalidates the same way. - const reader = { principal: { kind: 'owner' } } as Connection.PeerScope + const reader = loaded.connection.createPeer({ principal: { kind: 'owner' } }) const read = await loaded.webServer.readResource(new Request(`${base}/app.js`, { headers: { 'if-none-match': etag } }), reader) expect(read.status).toBe(304) diff --git a/packages/host/open-in-app/README.i18n.yaml b/packages/host/open-in-app/README.i18n.yaml index 97f08b56d1..8b7437f949 100644 --- a/packages/host/open-in-app/README.i18n.yaml +++ b/packages/host/open-in-app/README.i18n.yaml @@ -9,14 +9,14 @@ en: 91ff0fbf5f0b95b9 zh: 13a18d1a9bc38da0 /deepseek-ai-dsh-host-open-in-app/summary: - en: 894ed6d5eec55b71 - zh: b94ae1411966f145 + en: f6922aa70b598d29 + zh: d03dafb50850fafc /deepseek-ai-dsh-host-open-in-app/table-of-contents: en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-host-open-in-app/use-this-package: - en: c1217da1d6bdfd36 - zh: cbb05caa1a7764d0 + en: b800b5c32358b04f + zh: b7df359af6cd4c47 /deepseek-ai-dsh-host-open-in-app/use-this-package/when-to-choose-it: en: fcf8f52b6cf1f0dd zh: aed2366ccd0f112a @@ -33,8 +33,8 @@ en: 558e741770080c93 zh: 80482d355dc89cae /deepseek-ai-dsh-host-open-in-app/understand-the-implementation: - en: 0ebb9f5dfb251f11 - zh: d60bd93d5b3e6fb9 + en: 2245b83097ae2e1b + zh: 306ec4b3edfa3e47 /deepseek-ai-dsh-host-open-in-app/further-exploration: en: d5b6ee9a195a810b zh: 7825d6182be37255 diff --git a/packages/host/open-in-app/README.md b/packages/host/open-in-app/README.md index d32d42b93a..df763084c7 100644 --- a/packages/host/open-in-app/README.md +++ b/packages/host/open-in-app/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in-app/README.md) to let users open a workspace directory in an installed editor, Git GUI, terminal, or file manager. It offers a fixed application catalog and shows only entries that the host can verify; newly installed applications appear after restart, while missing launchers are removed when detected. Requests require the deployment's browser authentication and host-origin trust checks. Detection and launch commands use configurable deadlines and do not pass inherited credentials to launched applications. +Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in-app/README.md) to let users open a workspace directory in an installed editor, Git GUI, terminal, or file manager. It offers a fixed application catalog and shows only entries that the host can verify; newly installed applications appear after restart, while missing launchers are removed when detected. Requests require WebServer admission and an owner Peer; non-owner Peers receive 403 before application probing, icon access, or launch. Detection and launch commands use configurable deadlines and do not pass inherited credentials to launched applications. ## Table of Contents @@ -25,7 +25,7 @@ Use `dsh-host-open-in-app` with its [browser companion](../../client/ui-open-in- ## Use this package -Mount the package in a composition that carries `webServer`, `connection`, and `subprocess`, normally beside its browser surface [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.md); the pair puts an "Open In..." split button in the Web Session header whenever the host resolved at least one installed catalog application. +Mount the package in a composition that carries `webServer` and `subprocess`, normally beside its browser surface [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.md); the pair puts an "Open In..." split button in the Web Session header whenever the host resolved at least one installed catalog application. ### When to choose it @@ -79,7 +79,7 @@ Linux desktop-entry fields and icons use the shared [native-command](../../util/ The package splits into a data table and three roles. [`src/catalog.ts`](src/catalog.ts) is the compile-time table: each entry's per-platform locator chain (`fixed`, `app`, `xcode`, `cli`, `file`, `scan`, `app-paths`, `install-record`, `github-desktop`, `desktop`) plus, on Linux, the desktop-entry id owning its icon. [`src/resolver.ts`](src/resolver.ts) resolves the table against this host: one pass yields a map of catalog id to verified launch (primary and optional fallback argv plus the icon source), sharing one batched Windows-registry read; argv launches spawn detached with a credential-scrubbed environment (`scrubbedParentEnv`) minus the Desktop Host's `ELECTRON_RUN_AS_NODE`, plus explicit adapter entries, and keep Windows GUI processes visible unless the adapter hides a CLI process that launches the GUI separately. `shell-open` launches (the file managers) run the OS shell's open verb through `dsh-native-command`'s path opener under the same watch window, and a spawn `ENOENT` is classified as `missing` so the routes can refresh a stale entry. [`src/icons.ts`](src/icons.ts) extracts icons per platform: `plutil`/`sips` over the resolved bundle on macOS, a generated PowerShell `ExtractAssociatedIcon` script over the resolved executable on Windows (positional `-File` args keep paths out of command-line parsing), and desktop-entry/hicolor/pixmaps filesystem lookup on Linux. -[`src/index.ts`](src/index.ts) registers the three routes on `ctx.webServer`: `GET /open-in-app/apps` (the resolution map's keys), `GET /open-in-app/icon/` (the extracted icon, cached in memory per process), and `POST /open-in-app/open` (launches the map's verified launcher directly — never a re-detection). Every route asks the composition's `connection` service for a rejection first; the complete trust story — the Host/Origin fence and browser authentication — has one home in the [`src/index.ts`](src/index.ts) module comment. On top of that fence the open route validates its body at the wire: an `application/json` media type, a 64 KiB ceiling, a resolved-available catalog id, and an absolute path naming an existing directory. Resolution and icon commands run through [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.md) (argv, never a shell) under their respective deadlines; PATH names go through `ctx.subprocess.resolveExecutable()` in-process. +[`src/index.ts`](src/index.ts) registers the three routes on `ctx.webServer`: `GET /open-in-app/apps` (the resolution map's keys), `GET /open-in-app/icon/` (the extracted icon, cached in memory per process), and `POST /open-in-app/open` (launches the map's verified launcher directly — never a re-detection). Every route declares required WebServer admission and checks the supplied Peer's owner principal before accessing Host resources. The open route also validates its body at the wire: an `application/json` media type, a 64 KiB ceiling, a resolved-available catalog id, and an absolute path naming an existing directory. Resolution and icon commands run through [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.md) (argv, never a shell) under their respective deadlines; PATH names go through `ctx.subprocess.resolveExecutable()` in-process. diff --git a/packages/host/open-in-app/README.zh.md b/packages/host/open-in-app/README.zh.md index d14624c00d..3d4858c610 100644 --- a/packages/host/open-in-app/README.zh.md +++ b/packages/host/open-in-app/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -将 `dsh-host-open-in-app` 与其[浏览器配套包](../../client/ui-open-in-app/README.zh.md)一起使用,让用户能在已安装的编辑器、Git GUI、终端或文件管理器中打开 workspace 目录。本包提供固定的应用目录,并只显示主机能够验证的条目;新安装的应用在重启后出现,而检测到启动器缺失时会移除对应条目。请求须通过部署的浏览器认证与主机来源信任检查。检测与启动命令使用可配置的期限,且不会把继承的凭据传给启动的应用。 +将 `dsh-host-open-in-app` 与其[浏览器配套包](../../client/ui-open-in-app/README.zh.md)一起使用,让用户能在已安装的编辑器、Git GUI、终端或文件管理器中打开 workspace 目录。本包提供固定的应用目录,并只显示主机能够验证的条目;新安装的应用在重启后出现,而检测到启动器缺失时会移除对应条目。请求须通过 WebServer 准入并持有 owner Peer;非 owner Peer 在应用探测、图标访问或启动前收到403。检测与启动命令使用可配置的期限,且不会把继承的凭据传给启动的应用。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -把本包挂进携带 `webServer`、`connection` 与 `subprocess` 的组合,通常与其浏览器表面 [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.zh.md) 并排;只要主机解析出目录中至少一个已安装的应用,这对包就会在 Web 会话头部放上 "Open In..." 分体按钮。 +把本包挂进携带 `webServer` 与 `subprocess` 的组合,通常与其浏览器表面 [`dsh-client-ui-open-in-app`](../../client/ui-open-in-app/README.zh.md) 并排;只要主机解析出目录中至少一个已安装的应用,这对包就会在 Web 会话头部放上 "Open In..." 分体按钮。 ### 何时选择 @@ -79,7 +79,7 @@ Linux 桌面文件字段和图标使用共享的 [native-command](../../util/nat 本包拆为一张数据表与三个角色。[`src/catalog.ts`](src/catalog.ts) 是编译期表格:每个条目按平台的 locator 链(`fixed`、`app`、`xcode`、`cli`、`file`、`scan`、`app-paths`、`install-record`、`github-desktop`、`desktop`),以及 Linux 上拥有其图标的 desktop 条目 id。[`src/resolver.ts`](src/resolver.ts) 把表格解析到本机:一趟产出目录 id 到已验证启动的映射(主/回退 argv 加图标来源),共享一次批量的 Windows 注册表读取;argv 启动以清理过凭据的环境(`scrubbedParentEnv`)去掉 Desktop Host 的 `ELECTRON_RUN_AS_NODE` 后叠加适配器显式环境,再 detached 派生,Windows GUI 默认保持可见,只有负责另行打开 GUI 的 CLI 适配器会隐藏自己的进程。`shell-open` 启动(文件管理器)在同一看护窗口下经 `dsh-native-command` 的路径打开器执行 OS shell 的 open verb,spawn 的 `ENOENT` 被归类为 `missing`,让路由能刷新失效条目。[`src/icons.ts`](src/icons.ts) 按平台提取图标:macOS 在解析出的 bundle 上跑 `plutil`/`sips`,Windows 在解析出的可执行文件上跑生成的 PowerShell `ExtractAssociatedIcon` 脚本(`-File` 位置参数让路径不经过命令行解析),Linux 走 desktop 条目/hicolor/pixmaps 的文件系统查找。 -[`src/index.ts`](src/index.ts) 在 `ctx.webServer` 上注册三条路由:`GET /open-in-app/apps`(解析映射的 keys)、`GET /open-in-app/icon/`(提取的图标,进程内内存缓存)、`POST /open-in-app/open`(直接使用映射中已验证的启动器——绝不重新检测)。每条路由都先向组合的 `connection` 服务询问是否拒绝;完整的信任叙述——Host/Origin 栅栏与浏览器认证——唯一的出处在 [`src/index.ts`](src/index.ts) 的模块注释。在该栅栏之上,open 路由在 wire 边界校验请求体:`application/json` 媒体类型、64 KiB 上限、解析为可用的目录 id、指向现存目录的绝对路径。解析与图标命令经 [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.zh.md)(argv,绝不走 shell)在各自期限内执行;PATH 名称走 `ctx.subprocess.resolveExecutable()` 进程内解析。 +[`src/index.ts`](src/index.ts) 在 `ctx.webServer` 上注册三条路由:`GET /open-in-app/apps`(解析映射的 keys)、`GET /open-in-app/icon/`(提取的图标,进程内内存缓存)、`POST /open-in-app/open`(直接使用映射中已验证的启动器——绝不重新检测)。每条路由均声明 WebServer 认证准入,并在访问 Host 资源前检查传入 Peer 的 owner principal。open 路由还在 wire 边界校验请求体:`application/json` 媒体类型、64 KiB 上限、解析为可用的目录 id、指向现存目录的绝对路径。解析与图标命令经 [`@deepseek-ai/dsh-native-command`](../../util/native-command/README.zh.md)(argv,绝不走 shell)在各自期限内执行;PATH 名称走 `ctx.subprocess.resolveExecutable()` 进程内解析。 diff --git a/packages/host/open-in-app/package.json b/packages/host/open-in-app/package.json index 256d6919a8..29ce84dcd0 100644 --- a/packages/host/open-in-app/package.json +++ b/packages/host/open-in-app/package.json @@ -52,6 +52,7 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-host-webserver": "workspace:*" + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" } } diff --git a/packages/host/open-in-app/src/index.ts b/packages/host/open-in-app/src/index.ts index 8e8da91ec4..13baf80bae 100644 --- a/packages/host/open-in-app/src/index.ts +++ b/packages/host/open-in-app/src/index.ts @@ -4,12 +4,8 @@ * launch endpoint the browser split button * (`@deepseek-ai/dsh-client-ui-open-in-app`) posts to. * - * Security has one home, here. Every route asks the composition's - * `connection` service for a rejection first (`requestRejection`): its - * Host/Origin fence defeats DNS rebinding and cross-site calls, and its - * browser authentication (the login-token cookie) gates every caller before - * any resolution result, icon, or launch is reachable. On top of that fence - * the open route validates its body at the wire: an `application/json` media + * WebServer admits requests before dispatch; these routes require an owner Peer. + * The open route validates its body at the wire: an `application/json` media * type, a 64 KiB ceiling, string `app`/`path` fields, a resolved-available * catalog id, and an absolute path naming an existing directory. * @@ -43,8 +39,8 @@ export type * from './shared.ts' /** Cordis function-plugin name. */ export const name = 'open-in-app' -/** The route carrier, the trust fence guarding every route, and the PATH resolver. */ -export const inject = ['webServer', 'connection', 'subprocess'] +/** The route carrier and the PATH resolver. */ +export const inject = ['webServer', 'subprocess'] /** Open-in-app host configuration. */ export interface Config { @@ -75,16 +71,6 @@ export const Config: z = z.object({ launchWatchMs: boundedMs(), }) -/** Trust surface consumed here; the browser-side connection package owns the full type. */ -interface OpenInAppConnection { - requestRejection(request: { readonly headers: IncomingMessage['headers'] }): 401 | 403 | undefined -} - -/** The composition's connection service (typed locally: its package is browser-side). */ -function connectionOf(ctx: Context): OpenInAppConnection { - return Reflect.get(ctx, 'connection') as OpenInAppConnection -} - /** Open-route request bodies are tiny JSON objects; anything larger is hostile. */ const MAX_BODY_BYTES = 64 * 1024 @@ -134,7 +120,7 @@ function parseOpenBody(text: string): { app: string; path: string } | null { return typeof app === 'string' && typeof path === 'string' ? { app, path } : null } -/** Register the apps, icon, and open routes behind the connection trust fence. */ +/** Register owner-only apps, icon, and open routes. */ export function apply(ctx: Context, config: Config): void { const ssh = launchedThroughSsh(launchEnvironmentOf(ctx)) /** Test-seam facts completed with the composition's PATH resolver. */ @@ -181,20 +167,15 @@ export function apply(ctx: Context, config: Config): void { map.set(app.id, fresh) return fresh } - /** Answer an untrusted/unauthenticated request; true when it was rejected. */ - const rejected = (req: IncomingMessage, res: ServerResponse): boolean => { - const rejection = connectionOf(ctx).requestRejection(req) - if (rejection === undefined) return false - res.statusCode = rejection - res.end() - return true - } - ctx.effect(() => ctx.webServer.register({ kind: 'exact', + auth: 'required', path: OPEN_IN_APP_APPS_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'GET') { sendMethodNotAllowed(res, 'GET') return @@ -205,9 +186,13 @@ export function apply(ctx: Context, config: Config): void { ctx.effect(() => ctx.webServer.register({ kind: 'prefix', + auth: 'required', path: OPEN_IN_APP_ICON_PREFIX_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'GET') { sendMethodNotAllowed(res, 'GET') return @@ -240,9 +225,13 @@ export function apply(ctx: Context, config: Config): void { ctx.effect(() => ctx.webServer.register({ kind: 'exact', + auth: 'required', path: OPEN_IN_APP_OPEN_PATH, - handler: async (req, res) => { - if (rejected(req, res)) return + handler: async (req, res, peer) => { + if (peer?.principal.kind !== 'owner') { + sendJson(res, 403, { code: 'forbidden', message: 'owner access required' }) + return + } if (req.method !== 'POST') { sendMethodNotAllowed(res, 'POST') return diff --git a/packages/host/open-in-app/tests/host-routes.spec.ts b/packages/host/open-in-app/tests/host-routes.spec.ts index ff73819cc0..6327b3ff08 100644 --- a/packages/host/open-in-app/tests/host-routes.spec.ts +++ b/packages/host/open-in-app/tests/host-routes.spec.ts @@ -1,12 +1,11 @@ /** * Host routes over a real WebServer booted through the vendored Loader * (the REAL-composition requirement), asserting the HTTP surface: the - * connection trust fence, the one-pass catalog resolution the routes share, + * centralized admission, owner authorization, and one-pass catalog resolution, * icon serving with caching, the open route's wire validation, and the * stale-launcher (ENOENT) refresh. Host commands, launches, and PATH - * resolution are faked through the package `internals` seam; the connection - * service is a controllable stub (its real provider is the browser - * composition); the filesystem is real. + * resolution are faked through the package `internals` seam; admission returns + * a controllable Peer; the filesystem is real. */ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' @@ -18,7 +17,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import WebServer from '@deepseek-ai/dsh-host-webserver' +import WebServer, { type WebRoute } from '@deepseek-ai/dsh-host-webserver' import type { NativeCommandRunner } from '@deepseek-ai/dsh-native-command' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentLayerInput, @@ -27,9 +26,15 @@ import * as OpenInApp from '../src/index.ts' import { internals } from '../src/internals.ts' import type { OpenInAppLauncher } from '../src/resolver.ts' +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + openInAppAuthorizationTest: { readonly kind: 'open-in-app-authorization-test' } + } +} + let root: string | undefined let context: Context | undefined -/** Answer the connection stub gives every route until a test changes it. */ +/** Central admission decision until a test changes it. */ const trust: { rejection: 401 | 403 | undefined } = { rejection: undefined } afterEach(async () => { @@ -48,7 +53,7 @@ function pathTable(entries: Record = {}): (name: string) => Prom } /** Boot webserver + open-in-app rows through the real Loader. */ -async function boot(layers: readonly LaunchEnvironmentLayerInput[] = []): Promise { +async function boot(layers: readonly LaunchEnvironmentLayerInput[] = [], access: 'owner' | 'restricted' = 'owner'): Promise { internals.catalog = { env: {}, ...internals.catalog } root = await mkdtemp(join(tmpdir(), 'dsh-open-in-app-loader-')) const configPath = join(root, 'cordis.yml') @@ -68,7 +73,17 @@ async function boot(layers: readonly LaunchEnvironmentLayerInput[] = []): Promis context = new Context() context.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot(layers)) context.baseUrl = pathToFileURL(root).href + '/' - context.provide('connection', { requestRejection: () => trust.rejection } as never) + type Peer = NonNullable[2]> + const abort = new AbortController() + const peer: Peer = { + id: 'open-in-app-fixture' as Peer['id'], ctx: context, + principal: access === 'owner' ? { kind: 'owner' } : { kind: 'open-in-app-authorization-test' }, + signal: abort.signal, interactions: 'none', dispose: async () => { abort.abort() }, + } + context.effect(() => () => peer.dispose()) + context.on('webserver/authorize', () => trust.rejection === undefined + ? { kind: 'allow', peer } + : { kind: 'deny', status: trust.rejection }) // The plugin resolves PATH names through the composition's subprocess // capability; the not-found rejection is the provider's real signal. context.provide('subprocess', { @@ -172,7 +187,7 @@ describe('open-in-app host routes (real Loader composition)', () => { expect(Object.keys(OpenInApp).sort()).toEqual(['Config', 'apply', 'inject', 'name']) }) - it('answers the connection rejection on every route, before any resolution runs', async () => { + it('answers the admission rejection on every route, before any resolution runs', async () => { const run = vi.fn() internals.catalog = { platform: 'darwin', run, resolveExecutable: pathTable() } const base = await boot() @@ -188,6 +203,31 @@ describe('open-in-app host routes (real Loader composition)', () => { expect((await fetch(`${base}/open-in-app/apps`)).status).toBe(200) }) + it('refuses an authenticated non-owner before probing, reading icons, or launching', async () => { + const run = vi.fn() + const launch = vi.fn() + const resolveExecutable = vi.fn(pathTable()) + internals.catalog = { platform: 'darwin', run, launch, resolveExecutable } + const base = await boot([], 'restricted') + expect(context?.get('connection')).toBeUndefined() + for (const [path, options] of [ + ['/open-in-app/apps', {}], + ['/open-in-app/icon/finder', {}], + ['/open-in-app/open', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ app: 'finder', path: root }), + }], + ] as const) { + const response = await fetch(`${base}${path}`, options) + expect(response.status).toBe(403) + expect(response.headers.get('cache-control')).toBe('no-store') + await response.text() + } + expect(run).not.toHaveBeenCalled() + expect(resolveExecutable).not.toHaveBeenCalled() + expect(launch).not.toHaveBeenCalled() + }) + it('serves the resolved catalog, one cached icon, and launches from the same resolution', async () => { const launches: string[][] = [] const home = await mkdtemp(join(tmpdir(), 'dsh-open-in-app-home-')) diff --git a/packages/host/webserver/README.i18n.yaml b/packages/host/webserver/README.i18n.yaml index 7a81b0a0db..ac210137e2 100644 --- a/packages/host/webserver/README.i18n.yaml +++ b/packages/host/webserver/README.i18n.yaml @@ -24,11 +24,11 @@ en: 90352948bfdc1d99 zh: 35d148bf3bfcf76f /deepseek-ai-dsh-host-webserver/use-this-package/registering-routes: - en: 55b5f5751c46e0ee - zh: 6c609104f0798e01 + en: cf35827f67a2b78f + zh: f2259e857335d48f /deepseek-ai-dsh-host-webserver/use-this-package/the-fallback-seat: - en: 20e5a88f42ba38aa - zh: f20d2f4b3eba267a + en: 6e9a37ec076c8f50 + zh: 1e7c2291c6af9e61 /deepseek-ai-dsh-host-webserver/use-this-package/behavior-under-failure: en: 1bfff905b600f694 zh: 73f3b7704af686dc @@ -36,8 +36,8 @@ en: 42b15ac6321706aa zh: 4ed0861911abaf5d /deepseek-ai-dsh-host-webserver/understand-the-implementation/design-concept: - en: 88adbd5967b978d3 - zh: b4fabfd6f5df1b71 + en: 66e4cf637f553ddf + zh: 47d6d5ea8f7c3ac8 /deepseek-ai-dsh-host-webserver/understand-the-implementation/matching-and-lifecycle: en: 8589aba0cbaa1c76 zh: babf3b27b0cdb35e @@ -54,8 +54,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-host-webserver/known-limitations-and-deferred-work: - en: 9aa6b8cf92d5b506 - zh: 55ee3f6ad1cace50 + en: ac86e691a0994600 + zh: 99d2409389c9aa12 /deepseek-ai-dsh-host-webserver/known-limitations-and-deferred-work/dev-note: en: 245b35764295ba1e zh: a15b132b111bfef0 diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index 59313177e2..5288a1039b 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -58,13 +58,21 @@ Set `compression: 'gzip'` to wrap eligible socket-backed responses without chang ### Registering routes +WebServer events use the emitting WebServer as their Cordis subject. Ordinary listeners receive events only from the same `webServer` isolation; `{ global: true }` explicitly opts out. This applies to request handling, page injection, and entry-URL collection. Custom emitters must pass their WebServer instance as the subject too. + `register(route)` adds a named `exact` or `prefix` HTTP route, `registerUpgrade(route)` adds an upgrade route for an exact pathname, and both return a disposer that removes the registration. A duplicate path within either table throws — route patterns are a composition-level contract, so a collision is a misconfiguration. HTTP matching is exact over the whole table, then longest prefix, then the fallback; upgrades match exactly and unmatched connections are closed. -A named route may give `resource(request, peer?)` instead of `handler`: a function from a Fetch `Request` to a `Response`. Over HTTP only `GET` and `HEAD` reach it — any other method is answered 405 with `Allow: GET, HEAD` and its body is never read — and the request carries no Peer, the client's headers, and a URL that is the request target resolved against a placeholder origin; the client's authority stays only in the `host` header. The response is written back with backpressure and the gzip decision a handler's response gets; `HEAD` sends no body, and a client disconnect aborts `request.signal` and cancels the body. `readResource(request, peer)` returns the response the same URL would receive over HTTP, computed by the resource for `peer` (a `HEAD` read returns no body): it follows the HTTP match order, answers 404 when the path belongs to a handler or reaches a fallback that is unclaimed or a handler, answers 405 for a method other than `GET` or `HEAD`, and checks no cookie, Host, or Origin, so its caller admits the reader first. +A named route may give `resource(request, peer?)` instead of `handler`: a function from a Fetch `Request` to a `Response`. After admission, only `GET` and `HEAD` reach it; other methods receive 405 with `Allow: GET, HEAD`, without reading the body. The resource receives the admitted Peer, if any, and the client headers; its URL resolves the request target against a placeholder origin, leaving the client authority in `host`. Responses use backpressure and the same gzip handling as handlers; `HEAD` sends no body, and disconnect aborts `request.signal` and cancels the body. `readResource(request, peer)` dispatches in process with its explicitly admitted Peer: it checks no cookie, Host, or Origin, but a resolved `deny` returns 403. It follows HTTP match order, returns 404 for handlers or an unclaimed fallback, and 405 for non-GET/HEAD reads; HEAD reads return no body. + +HTTP requests pass through `webserver/request(request, response, next)` before route lookup. A listener owns the response or awaits `next()`; the request-error handler contains middleware failures. After matching, HTTP and upgrade routes resolve `auth`, either a fixed policy or a synchronous selector over request facts. `required` is the default and requires a live Peer; `anonymous` removes the credential requirement; `deny` returns 403 without dispatch. For other policies, synchronous `webserver/authorize(request, policy)` takes the first decision. Without a decision, `anonymous` allows and `required` returns 503. HTTP and upgrade admission refusals carry `Cache-Control: no-store`. Connection supplies source checks and ordered credential verification; its source checks also apply to anonymous routes. HTTP handlers receive `(req, res, peer?)`, upgrades `(req, socket, head, peer?)`, and resources keep their Peer parameter. In-process reads do not emit this event. + +Admitted upgrades pass through `webserver/upgrade(req, socket, head, peer, next)` before their registered protocol handler. The waterfall carries the already selected Peer, or `undefined` for anonymous admission; denied requests never enter it. A listener handles the Socket itself or awaits `next()` to delegate. WebServer awaits synchronous or asynchronous protocol handlers and contains rejected middleware or handlers by logging and destroying that Socket. Provider-specific Socket limits and credential cleanup belong to listeners, not to WebServer or Gateway. + +`webserver/entry-url(baseUrl, entries)` synchronously collects complete entry URLs for a supplied server base URL. Listeners append `{ label, url, open }` entries. WebApp emits it after readiness. WebApp owns ordered printing and the first eligible browser handoff. This event neither authenticates requests nor changes the listener or advertised-address configuration. ### The fallback seat -`registerFallback(handler)` or `registerFallback({ resource })` claims the one responder for every request no named route matches. A second registration throws; while no fallback is registered the server answers 404. In the shipped Web composition the [SPA dist server](../frontend-static/README.md) owns the seat and calls `renderIndex` on every index response it renders. +`registerFallback(handler)` or an object containing `handler` or `resource` and optional `auth` claims the one responder for unmatched requests. A bare handler still defaults to `required` admission. A second registration throws; an unclaimed seat returns 404. In the shipped Web composition the [SPA dist server](../frontend-static/README.md) owns the seat, selects authenticated index access and anonymous assets, and calls `renderIndex` for index responses. Index startup inputs are two layers, computed for the Peer the page speaks for. `collectIndexInjections(peer)` gathers a fresh injection table — one `webserver/index-inject` emit per call, passing `peer` to each subscriber, which pushes its current rows — and `renderIndex(html, peer)` renders those rows into the index.html body before applying the raw `tapIndex(transform)` transforms in registration order. A `script-preload` row renders an advisory classic-script preload link. Static deployments carry the same rows in their boot payload. `applyIndexTaps(html)` applies only the raw transforms; it is the escape hatch for markup no row expresses. @@ -82,7 +90,7 @@ A listen failure (for example EADDRINUSE) rejects plugin initialization with the ### Design concept -The package is a plain route registry whose only harness vocabulary is the Peer an index render speaks for: `WebServer` extends Cordis `Service` and holds three route tables plus the fallback slot, the raw index-tap list, and the `webserver/index-inject` event the index renderer gathers rows through. Index rendering composes two layers per response: `renderIndex` renders the fresh injection table, including advisory `script-preload` rows, into the body, then applies the raw taps in registration order; `applyIndexTaps` runs the taps alone. The upgrade handler owns the protocol handshake and connection contents; the webserver only delivers the raw socket and request. `host`, `port`, and `protocol` getters and `getOrigin()` expose composition-time facts other plugins adapt to (for example the directory-picker chooser), and an explicit `tls: null` normalizes to an unset listener, so `protocol` has a single source. +`WebServer` extends Cordis `Service` and owns matching, route admission, response delivery, and index rendering. Connection supplies source/credential decisions through an event rather than a WebServer dependency on a concrete authentication implementation. Index rendering gathers fresh `webserver/index-inject` rows, renders them, then applies raw taps. The upgrade handler owns protocol negotiation and connection contents after admission. Listener getters and `getOrigin()` expose configuration-derived transport facts; explicit `tls: null` means an HTTP listener. ### Matching and lifecycle @@ -129,7 +137,7 @@ None; this package neither assembles nor sends a provider request. These limits define where the server is intentionally minimal. They are current package constraints, not a task backlog. - **No certificate lifecycle** — `tls` serves the PEM files present at activation: the carrier never provisions, renews, or watches them, and it applies Node's default TLS policy. Replacing a certificate takes a reload. -- **No server-wide authentication or origin policy** — route owners such as `dsh-client-connection` enforce their own request policy. Binding a non-loopback address still exposes unprotected routes and static assets to that network. +- **Credential and source policy need an authorization listener** — the carrier enforces route declarations but verifies no credentials itself. Without a decision, authenticated routes return 503 and anonymous routes remain reachable; an active Connection listener applies source checks to both. - **Socket options are fixed** — config selects the bind host and port, while backlog and other socket settings remain internal until a deployment needs them. diff --git a/packages/host/webserver/README.zh.md b/packages/host/webserver/README.zh.md index aa8cde6345..0fce2aac11 100644 --- a/packages/host/webserver/README.zh.md +++ b/packages/host/webserver/README.zh.md @@ -58,13 +58,21 @@ kind: "package-reference" ### 注册路由 +WebServer 事件以发起它的 WebServer 为 Cordis subject。普通监听器仅接收相同 `webServer` isolation 中的事件;`{ global: true }` 明确跳过此过滤。请求处理、页面注入和入口 URL 收集均遵循此规则。自定义发起者也必须把自己的 WebServer 实例作为 subject 传入。 + `register(route)` 添加具名的 `exact`/`prefix` HTTP route,`registerUpgrade(route)` 为精确 pathname 添加 upgrade route,两者返回的 disposer 都会移除注册。同一张表内的重复路径会抛错——route 模式是组合层约定,冲突即配置错误。HTTP 匹配先在整张表中匹配精确 route,再匹配最长前缀,最后交给回退;upgrade 只做精确匹配,未命中连接直接关闭。 -具名 route 可以用 `resource(request, peer?)` 代替 `handler`:一个把 Fetch `Request` 映射为 `Response` 的函数。经 HTTP 时只有 `GET` 与 `HEAD` 能到达它——其他方法得到带 `Allow: GET, HEAD` 的 405,请求 body 从不读取——请求不带 Peer,携带客户端的 header,URL 是把请求目标按一个占位 origin 解析得到的,客户端的 authority 只保留在 `host` 头里。响应按背压写回,gzip 的处理与 handler 的响应相同;`HEAD` 不发送 body,客户端断开会中止 `request.signal` 并取消 body。`readResource(request, peer)` 返回同一 URL 经 HTTP 会得到的响应,由 resource 按 `peer` 计算(`HEAD` 读取不返回 body):它遵循 HTTP 的匹配顺序;路径属于 handler、或落到未认领或 handler 形式的回退时返回 404;`GET`、`HEAD` 以外的方法返回 405;不检查 cookie、Host 或 Origin,因此调用方须先准入读者。 +具名路由可以使用 `resource(request, peer?)` 代替 `handler`,将 Fetch `Request` 映射为 `Response`。准入后仅 `GET` 与 `HEAD` 可到达 resource;其他方法返回带 `Allow: GET, HEAD` 的405,不读取正文。resource 接收准入 Peer(若有)与客户端请求头;URL 将请求目标按占位 origin 解析,客户端 authority 保留在 `host` 中。响应按背压及与 handler 相同的 gzip 规则发送;`HEAD` 不发送正文,断开会中止 `request.signal` 并取消正文。`readResource(request, peer)` 使用显式准入的 Peer 在进程内分发,不检查 Cookie、Host 或 Origin,但解析出的 `deny` 返回403。它遵循 HTTP 匹配顺序,对 handler 或未认领回退返回404,对非 GET/HEAD 读取返回405;HEAD 读取不返回正文。 + +HTTP 请求在路由查找前经过 `webserver/request(request, response, next)`。监听器拥有响应或等待 `next()`,请求错误处理器容纳中间件异常。匹配后,HTTP 与 upgrade 路由解析 `auth`,可为固定策略或读取请求事实的同步选择器。默认 `required` 要求存活 Peer;`anonymous` 免凭据;`deny` 不分发,直接返回403。其余策略通过同步 `webserver/authorize(request, policy)` 采用首个决策。无人决策时匿名放行,认证返回503。HTTP 与 upgrade 的准入拒绝响应均携带 `Cache-Control: no-store`。Connection 提供来源检查与有序凭据验证;来源检查同样适用于匿名路由。HTTP handler 接收 `(req, res, peer?)`,upgrade 接收 `(req, socket, head, peer?)`,resource 保留已有 Peer 参数。进程内读取不触发此事件。 + +已准入的 upgrade 在已注册协议 handler 前经过 `webserver/upgrade(req, socket, head, peer, next)`。waterfall 携带已选定的 Peer,匿名准入可为 `undefined`;被拒绝的请求不会进入。监听器自行处理 Socket,或等待 `next()` 委派。WebServer 等待同步或异步协议 handler,并在中间件或 handler 拒绝时记录日志、销毁该 Socket。Provider 专属 Socket 限制与凭据清理属于监听器,不属于 WebServer 或 Gateway。 + +`webserver/entry-url(baseUrl, entries)` 根据传入的服务器基地址同步收集完整入口 URL。监听器追加 `{ label, url, open }` 入口。WebApp 在就绪后触发该事件。WebApp 拥有按序打印与首个可自动打开入口的浏览器交接。该事件不认证请求,也不改变监听器或公告地址配置。 ### 回退席位 -`registerFallback(handler)` 或 `registerFallback({ resource })` 认领所有未被具名 route 命中的请求的唯一一个应答方。第二次注册会抛错;没有注册回退时服务器回答 404。在随附的 Web 组合中,[SPA dist 服务器](../frontend-static/README.zh.md)拥有该席位,并对其渲染的每个 index 响应调用 `renderIndex`。 +`registerFallback(handler)` 或含 `handler`/`resource` 及可选 `auth` 的对象认领未匹配请求的唯一应答方。裸 handler 同样默认采用 `required` 准入。第二次注册抛错,未认领席位返回404。随附 Web 组合由 [SPA dist 服务器](../frontend-static/README.zh.md)持有席位,选择 index 认证访问及静态资源匿名访问,并为 index 响应调用 `renderIndex`。 index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexInjections(peer)` 收集一张全新的注入表——每次调用发一次 `webserver/index-inject` 事件,把 `peer` 传给每个订阅方,订阅方推入其当前行——`renderIndex(html, peer)` 先把这些行渲染进 index.html 正文,再按注册顺序应用原始 `tapIndex(transform)` 转换。`script-preload` 行会渲染为 classic script 的提示性 preload 链接。静态部署会在启动 payload 中携带同一批行。`applyIndexTaps(html)` 只应用原始转换;它是任何行都无法表达的标记的逃生口。 @@ -82,7 +90,7 @@ index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexI ### 设计理念 -本包是一个普通路由注册表,唯一的 harness 词汇是 index 渲染所代表的 Peer:`WebServer` 继承 Cordis `Service`,持有三张路由表、回退 slot、原始 index 转换列表,以及 `webserver/index-inject` 事件,index 渲染器经其收集行。index 渲染每次响应组合两层:`renderIndex` 先把包含提示性 `script-preload` 行的全新注入表渲染进正文,再按注册顺序应用原始转换;`applyIndexTaps` 只运行转换。upgrade handler 拥有协议握手与连接内容;webserver 只交付原始 socket 与 request。`host`、`port`、`protocol` getter 与 `getOrigin()` 暴露其他插件据以自适应的组合期事实(例如 directory-picker 选择器),而显式的 `tls: null` 会归一为未设置监听,使 `protocol` 只有一个来源。 +`WebServer` 继承 Cordis `Service`,拥有匹配、路由准入、响应交付与 index 渲染。Connection 通过事件提供来源/凭据决策,WebServer 不依赖具体认证实现。index 渲染收集新的 `webserver/index-inject` 行,渲染后执行原始转换。upgrade handler 在准入后拥有协议协商与连接内容。监听器 getter 与 `getOrigin()` 暴露配置决定的传输事实;显式 `tls: null` 表示 HTTP 监听器。 ### 匹配与生命周期 @@ -129,7 +137,7 @@ index 启动输入分两层,按页面所代表的 Peer 计算。`collectIndexI 这些限制说明服务器在何处有意保持最小。它们是当前包约束,不是任务积压。 - **不管理证书生命周期**:`tls` 只提供激活时存在的 PEM 文件——载体从不申请、续期或监视它们,并采用 Node 默认的 TLS 策略。替换证书需要重新加载。 -- **不提供服务器级认证或来源策略**:`dsh-client-connection` 等 route owner 会实施自己的请求策略。绑定非回环地址仍会向该网络公开未受保护的 route 与静态资源。 +- **凭据与来源策略需要准入监听器**——载体执行路由声明,但不自行验证凭据。无人决策时,认证路由返回503,匿名路由仍可访问;活动 Connection 监听器对两者均执行来源检查。 - **Socket 选项固定不变**:配置只选择绑定宿主与端口;在具体部署产生需求前,backlog 和其他 socket 设置仍保持内部实现。 diff --git a/packages/host/webserver/src/index.ts b/packages/host/webserver/src/index.ts index 6d613e8a49..3ed162f3b4 100644 --- a/packages/host/webserver/src/index.ts +++ b/packages/host/webserver/src/index.ts @@ -7,6 +7,8 @@ * Route handlers retain direct response ownership; a route or the fallback may * instead give a resource, which maps a Fetch `Request` to a `Response` and * also answers in-process reads. + * WebServer events use the instance as their subject: ordinary listeners follow + * its webServer isolation, while explicitly global listeners receive every instance. */ import { readFile } from 'node:fs/promises' @@ -27,11 +29,55 @@ import { renderIndexInjections, type IndexInjection } from './injections.ts' export { renderIndexInjections } from './injections.ts' export type { IndexInjection, IndexInjectionPlacement } from './injections.ts' +/** One application entry URL contributed for startup printing or browser handoff. */ +export interface WebEntryUrl { + /** Output prefix, such as `dsh web`. */ + readonly label: string + /** Complete entry URL, including any credentials required by its provider. */ + readonly url: string + /** Whether this entry is eligible for the application's automatic browser handoff. */ + readonly open: boolean +} + declare module '@deepseek-ai/cordis' { interface Context { webServer: WebServer } interface Events { + /** + * Collect complete entry URLs for an advertised server address. + * @param baseUrl - advertised server base URL without provider credentials. + * @param entries - entries appended synchronously in listener order. + * @mode emit + */ + 'webserver/entry-url'(baseUrl: string, entries: WebEntryUrl[]): void + /** + * Admit a matched request synchronously; the first decision wins. + * @param request - headers, target, transport, and available cancellation state. + * @param policy - resolved route policy; deny never emits this event. + * @mode bail + */ + 'webserver/authorize'(request: WebAuthRequest, policy: WebAuthPolicy): WebAdmission | undefined + /** + * Handle an HTTP request before named-route and fallback dispatch. + * @param request - original incoming HTTP request. + * @param response - response owned by the listener or its delegated handler. + * @param next - dispatch to the next listener or the matching route. + * @mode waterfall + */ + 'webserver/request'(request: IncomingMessage, response: ServerResponse, next: () => Promise): Promise + /** + * Handle an admitted upgrade before its registered protocol handler. + * @param request - original upgrade request. + * @param socket - transport owned by the upgrade. + * @param head - bytes received after the HTTP headers. + * @param peer - authenticated identity, absent for anonymous admission. + * @param next - delegate to the next listener or protocol handler. + * @mode waterfall + */ + 'webserver/upgrade'( + request: IncomingMessage, socket: Duplex, head: Buffer, peer: PeerScope | undefined, next: () => Promise, + ): Promise /** * Collect the structured index injection table for the page `peer` speaks * for. Emitted on every index render and every worker boot-payload @@ -45,6 +91,25 @@ declare module '@deepseek-ai/cordis' { } } +/** A route permits anonymous access, requires a live Peer, or refuses all access. */ +export type WebAuthPolicy = 'anonymous' | 'required' | 'deny' + +/** Authentication inputs shared by socket-backed and synthetic requests. */ +export interface WebAuthRequest { + headers: Headers | Readonly> + method?: string | undefined + url: URL + transport: 'http' | 'upgrade' + signal?: AbortSignal | undefined + socket?: { readonly destroyed: boolean } | undefined +} + +/** Fixed route policy or a synchronous policy selector. */ +export type WebAuthenticationRule = WebAuthPolicy | ((request: WebAuthRequest) => WebAuthPolicy) + +/** First authorization decision; authenticated access requires a live Peer. */ +export type WebAdmission = { kind: 'allow'; peer?: PeerScope } | { kind: 'deny'; status: 401 | 403 | 503 } + /** Route match kind: 'exact' matches the pathname verbatim; 'prefix' p matches p and p/. */ export type WebRouteKind = 'exact' | 'prefix' @@ -54,12 +119,14 @@ export interface WebRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */ - handler: (req: IncomingMessage, res: ServerResponse) => void | Promise + handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } /** - * Answers one GET or HEAD request with a Fetch response. An HTTP request - * arrives without a Peer and carries the client's headers; an in-process + * Answers one GET or HEAD request with a Fetch response and its admitted Peer. + * Anonymous HTTP admission may omit the Peer; an in-process * {@link WebServer.readResource} read passes the Peer its caller admitted. */ export type WebResource = (request: Request, peer?: PeerScope) => Promise @@ -71,14 +138,21 @@ export interface WebResourceRoute { path: string /** Answers HTTP GET and HEAD requests and in-process reads. */ resource: WebResource + /** Defaults to required; in-process reads still enforce deny. */ + auth?: WebAuthenticationRule } +/** The unmatched-request responder; omitted auth requires authentication. */ +export type WebFallback = Pick | Pick + /** One exact-path HTTP upgrade registration. */ export interface WebUpgradeRoute { /** Absolute pathname, no trailing slash. */ path: string /** Owns protocol negotiation and the upgraded socket after dispatch. */ - handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => void | Promise + handler: (req: IncomingMessage, socket: Duplex, head: Buffer, peer?: PeerScope) => void | Promise + /** Defaults to required. Anonymous handlers may receive no Peer. */ + auth?: WebAuthenticationRule } /** @@ -352,7 +426,8 @@ async function writeResponse(res: ServerResponse, response: Response, head: bool * initialization, and the boot process reports the failed fiber. Route * registration order does not affect requests because configured named routes * must be distinct, and a request no named route matches is answered 404 - * until the fallback owner registers. + * until the fallback owner registers. HTTP and upgrade admission refusals + * carry `Cache-Control: no-store`. */ export class WebServer extends Service { static Config: z = z.object({ @@ -388,7 +463,7 @@ export class WebServer extends Service { */ private readonly tlsConnections = new Set() private readonly indexTaps: ((html: string) => string)[] = [] - private fallback: WebRoute['handler'] | Pick | undefined + private fallback: WebFallback | undefined private server!: Server private listenedPort: number | undefined private readonly gzip: NodeMiddleware | undefined @@ -471,14 +546,14 @@ export class WebServer extends Service { * composition). One owner only — a second registration throws, because two * fallbacks cannot compose. * @param fallback - a handler owning the full response lifecycle of - * unmatched requests, or `{ resource }` answering them. + * unmatched requests, or an object declaring `handler` or `resource` and auth. * @returns the disposer releasing the seat. */ - registerFallback(fallback: WebRoute['handler'] | Pick): () => void { + registerFallback(fallback: WebRoute['handler'] | WebFallback): () => void { if (this.fallback !== undefined) { throw new Error('webserver: fallback already registered') } - this.fallback = fallback + this.fallback = typeof fallback === 'function' ? { handler: fallback } : fallback return () => { this.fallback = undefined } } @@ -488,6 +563,7 @@ export class WebServer extends Service { * path picks the responder by the HTTP match order — exact, longest prefix, * then the fallback — and only a resource answers. This method checks no * cookie, Host, or Origin: the caller admits the reader before reading. + * A resolved deny policy returns 403 even for an explicitly admitted Peer. * @param request - the read; its URL path selects the responder. * @param peer - the Peer the read speaks for, passed to the resource. * @returns the resource's response, without a body for HEAD as over HTTP; @@ -501,8 +577,12 @@ export class WebServer extends Service { if (request.method !== 'GET' && request.method !== 'HEAD') { return new Response(null, { status: 405, headers: { allow: RESOURCE_METHODS } }) } - const responder = this.responderFor(new URL(request.url).pathname) - if (typeof responder !== 'object' || !('resource' in responder)) return new Response(null, { status: 404 }) + const url = new URL(request.url) + const responder = this.responderFor(url.pathname) + if (responder === undefined || !('resource' in responder)) return new Response(null, { status: 404 }) + if (this.authPolicy(responder.auth, { headers: request.headers, method: request.method, url, transport: 'http', signal: request.signal }) === 'deny') { + return new Response(null, { status: 403 }) + } const response = await responder.resource(request, peer) if (request.method === 'GET') return response await response.body?.cancel() @@ -536,9 +616,34 @@ export class WebServer extends Service { res.end() return } - if (typeof responder === 'function') await responder(req, res) - else if ('resource' in responder) await this.serveResource(req, res, target, responder.resource) - else await responder.handler(req, res) + const abort = new AbortController() + const cleanup = (): void => { + res.off('close', onClose) + res.off('finish', cleanup) + } + const onClose = (): void => { + abort.abort() + cleanup() + } + res.once('close', onClose) + res.once('finish', cleanup) + try { + const request: WebAuthRequest = { + headers: req.headers, method: req.method, url: target, transport: 'http', + signal: abort.signal, socket: req.socket, + } + const admission = this.authorize(request, responder.auth) + if (abort.signal.aborted || request.socket?.destroyed) return + if (admission.kind === 'deny') { + res.writeHead(admission.status, { 'Cache-Control': 'no-store' }) + res.end(admission.status === 401 ? 'unauthorized' : admission.status === 503 ? 'authentication unavailable' : 'forbidden') + return + } + if ('resource' in responder) await this.serveResource(req, res, target, responder.resource, abort.signal, admission.peer) + else await responder.handler(req, res, admission.peer) + } finally { + if (res.writableEnded || abort.signal.aborted) cleanup() + } } // Last-resort guard: handle() rejecting would otherwise be an unhandled // rejection killing the process on one malformed request (bad %-escape, @@ -546,7 +651,8 @@ export class WebServer extends Service { // never a process exit. const listener = (req: IncomingMessage, res: ServerResponse): void => { const next = (): void => { - void handle(req, res).catch((err: unknown) => { + const dispatch = async (): Promise => { await this.ctx.waterfall(this, 'webserver/request', req, res, () => handle(req, res)) } + void dispatch().catch((err: unknown) => { this.ctx.logger.warn(err instanceof Error ? err : new Error(String(err))) if (res.headersSent) { res.destroy() @@ -592,9 +698,11 @@ export class WebServer extends Service { this.upgradedSockets.delete(socket) }) let route: WebUpgradeRoute | undefined + let target: URL try { /* v8 ignore next -- node:http always sets url on server requests. */ - route = this.upgrades.get(new URL(req.url ?? '/', 'http://x').pathname) + target = new URL(req.url ?? '/', 'http://x') + route = this.upgrades.get(target.pathname) } catch (error) { this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error))) socket.destroy() @@ -605,8 +713,26 @@ export class WebServer extends Service { return } this.upgradedSockets.add(socket) + const abort = new AbortController() + socket.once('close', () => { abort.abort() }) try { - Promise.resolve(route.handler(req, socket, head)).catch((error: unknown) => { + const admission = this.authorize({ + headers: req.headers, method: req.method, url: target, transport: 'upgrade', + signal: abort.signal, socket, + }, route.auth) + if (abort.signal.aborted || socket.destroyed) return + if (admission.kind === 'deny') { + const reason = { 401: 'Unauthorized', 403: 'Forbidden', 503: 'Service Unavailable' }[admission.status] + const body = reason.toLowerCase() + socket.end(`HTTP/1.1 ${String(admission.status)} ${reason}\r\nConnection: close\r\nCache-Control: no-store\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${String(Buffer.byteLength(body))}\r\n\r\n${body}`) + return + } + const dispatch = async (): Promise => { + await this.ctx.waterfall(this, 'webserver/upgrade', req, socket, head, admission.peer, async () => { + if (!socket.destroyed) await route.handler(req, socket, head, admission.peer) + }) + } + void dispatch().catch((error: unknown) => { this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error))) socket.destroy() }) @@ -647,10 +773,26 @@ export class WebServer extends Service { * The responder for one request path, shared by HTTP requests and * {@link readResource}: the matched named route, otherwise the fallback. */ - private responderFor(pathname: string): WebRoute | WebResourceRoute | WebRoute['handler'] | Pick | undefined { + private responderFor(pathname: string): WebFallback | undefined { return this.match(pathname) ?? this.fallback } + private authPolicy(auth: WebAuthenticationRule | undefined, request: WebAuthRequest): WebAuthPolicy { + return typeof auth === 'function' ? auth(request) : auth ?? 'required' + } + + private authorize(request: WebAuthRequest, auth: WebAuthenticationRule | undefined): WebAdmission { + const policy = this.authPolicy(auth, request) + if (policy === 'deny') return { kind: 'deny', status: 403 } + const admission: WebAdmission = this.ctx.bail(this, 'webserver/authorize', request, policy) + ?? (policy === 'anonymous' ? { kind: 'allow' } : { kind: 'deny', status: 503 }) + if (admission.kind === 'allow') { + if (policy === 'required' && admission.peer === undefined) return { kind: 'deny', status: 503 } + if (admission.peer?.signal.aborted) return { kind: 'deny', status: 401 } + } + return admission + } + /** Longest-prefix-wins over the prefix table after an exact-table miss. */ private match(pathname: string): WebRoute | WebResourceRoute | undefined { const exact = this.exact.get(pathname) @@ -666,13 +808,15 @@ export class WebServer extends Service { /** * Answer one HTTP exchange from a resource. Only GET and HEAD reach it; * any other method receives 405 and its request body is never read. The - * request becomes a Fetch `Request` without a Peer whose URL is the request + * request becomes a Fetch `Request` whose URL is the request * target resolved against a placeholder origin, as the match reads it; the * client's authority stays only in the `host` header. The connection * closing before this method ends the response aborts the request signal * and cancels the response body. */ - private async serveResource(req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResource): Promise { + private async serveResource( + req: IncomingMessage, res: ServerResponse, target: URL, resource: WebResource, signal: AbortSignal, peer?: PeerScope, + ): Promise { if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: RESOURCE_METHODS }) res.end() @@ -682,24 +826,9 @@ export class WebServer extends Service { for (const [name, value] of Object.entries(req.headers)) { for (const item of typeof value === 'string' ? [value] : value ?? []) headers.append(name, item) } - const abort = new AbortController() - // An own flag, not `writableEnded`: the Web Worker tunnel marks an aborted - // response ended before it emits `close`. - let ended = false - const onClose = (): void => { - if (!ended) abort.abort() - } - res.on('close', onClose) - try { - const response = await resource(new Request(target, { method: req.method, headers, signal: abort.signal })) - await writeResponse(res, response, req.method === 'HEAD', abort.signal) - if (!abort.signal.aborted) { - ended = true - res.end() - } - } finally { - res.off('close', onClose) - } + const response = await resource(new Request(target, { method: req.method, headers, signal }), peer) + await writeResponse(res, response, req.method === 'HEAD', signal) + if (!signal.aborted) res.end() } /** @@ -724,7 +853,7 @@ export class WebServer extends Service { */ collectIndexInjections(peer: PeerScope): IndexInjection[] { const table: IndexInjection[] = [] - this.ctx.emit('webserver/index-inject', table, peer) + this.ctx.emit(this, 'webserver/index-inject', table, peer) return table } diff --git a/packages/host/webserver/tests/event-isolation.host.spec.ts b/packages/host/webserver/tests/event-isolation.host.spec.ts new file mode 100644 index 0000000000..5d7828d1fb --- /dev/null +++ b/packages/host/webserver/tests/event-isolation.host.spec.ts @@ -0,0 +1,88 @@ +/** WebServer request and page events follow each instance's service isolation. */ +import { once } from 'node:events' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { connect } from 'node:net' +import { Context } from '@deepseek-ai/cordis' +import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished } from 'vitest' +import WebServer from '../src/index.ts' + +it('filters HTTP, upgrade, and index listeners while retaining explicitly global listeners', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const isolated = ctx.isolate('webServer') + await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + await isolated.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await() + const servers = [ctx.webServer, isolated.webServer] + const calls: string[] = [] + ctx.on('webserver/request', async function (this: unknown, _req: IncomingMessage, _res: ServerResponse, next: () => Promise) { + expect(this).toBeInstanceOf(WebServer) + calls.push('global:request') + await next() + }, { global: true }) + ctx.on('webserver/authorize', () => { calls.push('global:authorize') }, { global: true }) + ctx.on('webserver/upgrade', async (_req, _socket, _head, _peer, next) => { + calls.push('global:upgrade') + await next() + }, { global: true }) + ctx.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'global', name: 'globalEntry', value: true }) + }, { global: true }) + + for (const [scope, label] of [[ctx, 'main'], [isolated, 'isolated']] as const) { + scope.on('webserver/request', async (_req, _res, next) => { + calls.push(`${label}:request`) + await next() + }) + scope.on('webserver/authorize', () => { + calls.push(`${label}:authorize`) + return { kind: 'allow' } + }) + scope.on('webserver/upgrade', async (_req, _socket, _head, _peer, next) => { + calls.push(`${label}:upgrade`) + await next() + }) + scope.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'global', name: label, value: true }) + }) + scope.effect(() => scope.webServer.register({ + kind: 'exact', path: '/probe', auth: 'anonymous', + handler(_req, res) { res.end(label) }, + })) + scope.effect(() => scope.webServer.registerUpgrade({ + path: '/socket', auth: 'anonymous', + handler(_req, socket) { + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: probe\r\n\r\n') + }, + })) + } + + for (const [index, label] of ['main', 'isolated'].entries()) { + const server = servers[index]! + calls.length = 0 + const response = await fetch(`${server.getOrigin()}/probe`) + expect(await response.text()).toBe(label) + expect(calls).toEqual(['global:request', `${label}:request`, 'global:authorize', `${label}:authorize`]) + + calls.length = 0 + const socket = connect(server.port!, '127.0.0.1') + const closed = new Promise((resolve) => { socket.once('close', () => { resolve() }) }) + onTestFinished(async () => { socket.destroy(); await closed }) + await once(socket, 'connect') + let output = '' + socket.setEncoding('utf8').on('data', (data: string) => { output += data }) + socket.write('GET /socket HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: probe\r\n\r\n') + await closed + expect(output).toContain('101 Switching Protocols') + expect(calls).toEqual(['global:authorize', `${label}:authorize`, 'global:upgrade', `${label}:upgrade`]) + + const peer: PeerScope = { + id: label as PeerScope['id'], ctx, principal: { kind: 'owner' }, interactions: 'none', + signal: new AbortController().signal, async dispose() {}, + } + expect(server.collectIndexInjections(peer)).toEqual([ + { kind: 'global', name: 'globalEntry', value: true }, + { kind: 'global', name: label, value: true }, + ]) + } +}) diff --git a/packages/host/webserver/tests/webserver.spec.ts b/packages/host/webserver/tests/webserver.spec.ts index 783b0c86dc..0ebf4abec8 100644 --- a/packages/host/webserver/tests/webserver.spec.ts +++ b/packages/host/webserver/tests/webserver.spec.ts @@ -15,7 +15,7 @@ import { Agent, request as httpsRequest } from 'node:https' import { connect, createServer as createTcpServer, type AddressInfo } from 'node:net' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import type { Duplex } from 'node:stream' +import { Duplex } from 'node:stream' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context, FiberState } from '@deepseek-ai/cordis' @@ -24,6 +24,7 @@ import Include from '@deepseek-ai/cordis-plugin-include' import type { PeerScope } from '@deepseek-ai/dsh-typert-protocol' import HttpServer, { bindUrlHost, isLoopbackHost, normalizeBindAddress, renderIndexInjections, type TlsConfig, type WebResource, type WebRoute, + type WebAuthRequest, } from '../src/index.ts' import { materializeTlsFixture, type TlsFixture } from './tls-fixture.ts' @@ -247,6 +248,279 @@ function tlsUpgrade(port: number | undefined, path: string, ca: string): Promise } describe('real Loader composition', () => { + it.each([401, 403, 503] as const)('marks HTTP and upgrade admission refusals %s as non-cacheable', async (status) => { + const ctx = await loadComposition() + const handler = vi.fn() + ctx.webServer.register({ kind: 'exact', path: '/private', handler }) + ctx.webServer.registerUpgrade({ path: '/private', handler }) + ctx.on('webserver/authorize', () => ({ kind: 'deny', status })) + + const response = await request(ctx.webServer.port, '/private') + expect(response.status).toBe(status) + expect(response.headers.get('cache-control')).toBe('no-store') + const upgraded = await rawExchange(ctx.webServer.port, + 'GET /private HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + expect(upgraded).toMatch(new RegExp(`^HTTP/1.1 ${String(status)} `, 'u')) + expect(upgraded).toContain('\r\nCache-Control: no-store\r\n') + expect(handler).not.toHaveBeenCalled() + }) + + it('authenticates matched HTTP routes once and forwards the admitted Peer', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const abort = new AbortController() + const peer: PeerScope = { + id: 'route-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: abort.signal, + interactions: 'none', async dispose() { abort.abort() }, + } + const reached: (PeerScope | undefined)[] = [] + const handler: WebRoute['handler'] = (_req, res, admitted) => { reached.push(admitted); res.end('allowed') } + server.register({ kind: 'exact', path: '/private', handler }) + server.register({ kind: 'prefix', path: '/public', auth: 'anonymous', handler }) + server.register({ kind: 'exact', path: '/public/secret', auth: 'deny', handler }) + expect(await request(server.port, '/private')).toMatchObject({ status: 503, body: 'authentication unavailable' }) + expect((await request(server.port, '/public')).status).toBe(200) + expect(reached).toEqual([undefined]) + const seen: WebAuthRequest[] = [] + const listener = ctx.plugin({ apply(scope: Context) { + scope.on('webserver/authorize', (incoming, policy) => { + seen.push(incoming) + if (policy === 'anonymous') return { kind: 'allow' } + if (incoming.headers instanceof Headers || incoming.headers.authorization !== 'Bearer valid') return { kind: 'deny', status: 401 } + return { kind: 'allow', peer } + }) + } }) + await listener.await() + const later = vi.fn(() => ({ kind: 'deny' as const, status: 403 as const })) + const removeLater = ctx.on('webserver/authorize', later) + expect((await request(server.port, '/missing')).status).toBe(404) + expect(await request(server.port, '/public/secret')).toMatchObject({ status: 403, body: 'forbidden' }) + expect(seen).toHaveLength(0) + expect((await request(server.port, '/private')).status).toBe(401) + expect((await request(server.port, '/private', { headers: { authorization: 'Bearer valid' } })).status).toBe(200) + expect(reached.at(-1)).toBe(peer) + expect(seen.at(-1)).toMatchObject({ method: 'GET', transport: 'http' }) + expect(seen.at(-1)?.url.pathname).toBe('/private') + expect(seen.at(-1)?.socket?.destroyed).toBe(false) + expect(later).not.toHaveBeenCalled() + await peer.dispose() + expect((await request(server.port, '/private', { headers: { authorization: 'Bearer valid' } })).status).toBe(401) + await listener.dispose() + removeLater() + expect(await request(server.port, '/private')).toMatchObject({ status: 503, body: 'authentication unavailable' }) + }) + + it('resolves selectors for resources and fallback while trusting explicit in-process Peers', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const peer: PeerScope = { + id: 'resource-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: new AbortController().signal, + interactions: 'none', async dispose() {}, + } + const resource = vi.fn(async (_request: Request, admitted?: PeerScope) => { + expect(admitted).toBe(peer) + return new Response('resource') + }) + server.register({ kind: 'exact', path: '/resource', resource, auth: incoming => incoming.url.searchParams.has('deny') ? 'deny' : 'required' }) + const authorize = vi.fn(() => ({ kind: 'allow' as const, peer })) + ctx.on('webserver/authorize', authorize) + expect(await request(server.port, '/resource', { method: 'HEAD' })).toMatchObject({ status: 200, body: '' }) + expect(authorize).toHaveBeenCalledTimes(1) + expect(resource).toHaveBeenCalledTimes(1) + const direct = await server.readResource(new Request('http://reader.invalid/resource', { headers: { authorization: 'invalid' } }), peer) + expect(await direct.text()).toBe('resource') + expect(authorize).toHaveBeenCalledTimes(1) + expect((await server.readResource(new Request('http://reader.invalid/resource?deny'), peer)).status).toBe(403) + expect((await request(server.port, '/resource?deny', { method: 'HEAD' })).status).toBe(403) + expect(resource).toHaveBeenCalledTimes(2) + expect(authorize).toHaveBeenCalledTimes(1) + const release = server.registerFallback({ auth: incoming => incoming.url.pathname === '/blocked' ? 'deny' : 'required', resource }) + expect((await request(server.port, '/fallback')).body).toBe('resource') + expect((await request(server.port, '/blocked')).status).toBe(403) + release() + }) + + it('requires admission for bare fallback handlers and rejects an allow without a required Peer', async () => { + const ctx = await loadComposition() + const reached = vi.fn((_req, res) => { res.end('unexpected') }) + ctx.webServer.registerFallback(reached) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(503) + const stop = ctx.on('webserver/authorize', () => ({ kind: 'allow' })) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(503) + stop() + ctx.on('webserver/authorize', () => { throw new Error('authorization failed') }) + expect((await request(ctx.webServer.port, '/fallback')).status).toBe(400) + expect(reached).not.toHaveBeenCalled() + }) + + it('authorizes upgrade routes before dispatch and forwards their Peer', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const peer: PeerScope = { + id: 'upgrade-auth' as PeerScope['id'], ctx, principal: { kind: 'owner' }, signal: new AbortController().signal, + interactions: 'none', async dispose() {}, + } + const stages: string[] = [] + const removeMiddleware = ctx.on('webserver/upgrade', async (_request, _socket, _head, incomingPeer, next) => { + expect(incomingPeer).toBe(peer) + stages.push('before') + await next() + stages.push('after') + }) + let admitted: PeerScope | undefined + server.registerUpgrade({ path: '/private', handler(_req, socket, _head, incoming) { + admitted = incoming + stages.push('handler') + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + } }) + server.registerUpgrade({ path: '/denied', auth: 'deny', handler() { throw new Error('must not dispatch') } }) + const exchange = (path: string) => rawExchange(server.port, `GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n`) + expect(await exchange('/private')).toContain('503 Service Unavailable') + expect(await exchange('/denied')).toContain('403 Forbidden') + expect(await exchange('/missing')).toBe('') + const reject = ctx.on('webserver/authorize', () => ({ kind: 'deny', status: 401 })) + expect(await exchange('/private')).toContain('401 Unauthorized') + expect(stages).toEqual([]) + reject() + let incoming: WebAuthRequest | undefined + const allow = ctx.on('webserver/authorize', (request) => { incoming = request; return { kind: 'allow', peer } }) + expect(await exchange('/private?x=1')).toContain('101 Switching Protocols') + expect(admitted).toBe(peer) + expect(stages).toEqual(['before', 'handler', 'after']) + removeMiddleware() + const veto = ctx.on('webserver/upgrade', async (_req, socket) => { socket.end('HTTP/1.1 409 Conflict\r\n\r\n') }) + expect(await exchange('/private?x=1')).toContain('409 Conflict') + expect(stages).toEqual(['before', 'handler', 'after']) + veto() + expect(incoming?.url.search).toBe('?x=1') + expect(incoming?.transport).toBe('upgrade') + await vi.waitFor(() => { expect(incoming?.signal?.aborted).toBe(true) }) + allow() + ctx.on('webserver/authorize', () => { throw new Error('upgrade authorization failed') }) + expect(await exchange('/private')).toBe('') + }) + + it('propagates HTTP cancellation to authorization and the resource without reauthenticating', async () => { + const ctx = await loadComposition() + const cancelled = Promise.withResolvers() + let admissionSignal: AbortSignal | undefined + let resourceSignal: AbortSignal | undefined + ctx.on('webserver/authorize', (incoming) => { admissionSignal = incoming.signal; return { kind: 'allow' } }) + ctx.webServer.register({ kind: 'exact', path: '/stream', auth: 'anonymous', resource: async (incoming) => { + resourceSignal = incoming.signal + return new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode('ready')) }, + cancel() { cancelled.resolve(undefined) }, + })) + } }) + const abort = new AbortController() + const response = await fetch(`${ctx.webServer.getOrigin()}/stream`, { signal: abort.signal }) + await response.body!.getReader().read() + expect(admissionSignal?.aborted).toBe(false) + abort.abort() + await cancelled.promise + expect(admissionSignal?.aborted).toBe(true) + expect(resourceSignal?.aborted).toBe(true) + }) + + it('contains selector failures and never dispatches a synchronously closed request', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const handler = vi.fn((_req, res) => { res.end('unexpected') }) + server.register({ kind: 'exact', path: '/throws', auth() { throw new Error('selector failed') }, handler }) + expect((await request(server.port, '/throws')).status).toBe(400) + server.register({ kind: 'exact', path: '/closed', auth: 'anonymous', handler }) + let closeRequest = (): void => {} + ctx.on('webserver/request', async (req, _res, next) => { closeRequest = () => { req.socket.destroy() }; await next() }) + ctx.on('webserver/authorize', () => { closeRequest(); return { kind: 'allow' } }) + expect(await rawExchange(server.port, 'GET /closed HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n')).toBe('') + expect(handler).not.toHaveBeenCalled() + }) + + it('dispatches anonymous upgrades without a provider and contains selector and handler failures', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const exchange = (path: string) => rawExchange(server.port, `GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n`) + server.registerUpgrade({ path: '/public', auth: 'anonymous', handler(_req, socket, _head, peer) { + expect(peer).toBeUndefined() + socket.end('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') + } }) + expect(await exchange('/public')).toContain('101 Switching Protocols') + server.registerUpgrade({ path: '/selector', auth() { throw new Error('upgrade selector failed') }, handler() {} }) + server.registerUpgrade({ path: '/sync', auth: 'anonymous', handler() { throw new Error('sync upgrade failed') } }) + server.registerUpgrade({ path: '/async', auth: 'anonymous', async handler() { throw new Error('async upgrade failed') } }) + for (const path of ['/selector', '/sync', '/async']) expect(await exchange(path)).toBe('') + expect(await exchange('http://[')).toBe('') + }) + + it('does not dispatch upgrades destroyed during synchronous admission', async () => { + const ctx = await loadComposition() + const handler = vi.fn() + ctx.webServer.registerUpgrade({ path: '/closed', auth: 'anonymous', handler }) + const socket = new Duplex({ read() {}, write(_chunk, _encoding, callback) { callback() } }) + const closed = once(socket, 'close') + ctx.on('webserver/authorize', (incoming) => { + expect(incoming.socket).toBe(socket) + socket.destroy() + return { kind: 'allow' } + }) + const server = Reflect.get(ctx.webServer, 'server') as { emit(event: 'upgrade', req: object, socket: Duplex, head: Buffer): boolean } + server.emit('upgrade', { url: '/closed', method: 'GET', headers: {} }, socket, Buffer.alloc(0)) + await closed + expect(handler).not.toHaveBeenCalled() + }) + + it('runs HTTP middleware before dispatch and delegates only through next', async () => { + const ctx = await loadComposition() + const server = ctx.webServer + const calls: string[] = [] + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource', resource: async () => { + calls.push('resource') + return new Response('resource') + } }) + const middleware = ctx.plugin({ apply(scope: Context) { + scope.on('webserver/request', async (req, res, next) => { + calls.push('before') + if (req.url === '/exchange') { + res.writeHead(303, { location: './', 'set-cookie': 'fixture=valid' }) + res.end() + return + } + await next() + calls.push('after') + }) + } }) + await middleware.await() + expect((await request(server.port, '/resource')).body).toBe('resource') + expect(calls).toEqual(['before', 'resource', 'after']) + calls.length = 0 + const response = await fetch(`http://127.0.0.1:${String(server.port)}/exchange`, { redirect: 'manual' }) + expect(response.status).toBe(303) + expect(response.headers.get('set-cookie')).toBe('fixture=valid') + await response.text() + expect(calls).toEqual(['before']) + calls.length = 0 + const peer = { principal: { kind: 'owner' } } as PeerScope + expect(await (await server.readResource(new Request('http://reader.invalid/resource'), peer)).text()).toBe('resource') + expect(calls).toEqual(['resource']) + await middleware.dispose() + calls.length = 0 + expect((await request(server.port, '/resource')).body).toBe('resource') + expect(calls).toEqual(['resource']) + }) + + it('contains synchronous middleware failures before reaching the route', async () => { + const ctx = await loadComposition() + let reached = false + ctx.webServer.register({ auth: 'anonymous', kind: 'exact', path: '/guarded', handler(_req, res) { + reached = true + res.end('unexpected') + } }) + ctx.on('webserver/request', () => { throw new Error('middleware failed') }) + expect((await request(ctx.webServer.port, '/guarded')).status).toBe(400) + expect(reached).toBe(false) + }) + it('accepts one concrete IP literal, keeping an IPv6 zone for listen', () => { for (const host of ['127.0.0.1', '10.1.2.3', '0.1.2.3', '::1', 'fd00::1', '::ffff:10.1.2.3', '::ffff:0.1.2.3', '0:0:0:0:0:0:0:1', 'fe80::1%lo', '::0.0.0.1', '::0.0.0.1%lo', '::127.0.0.1']) { expect(HttpServer.Config({ host, port: 0 }).host).toBe(host) @@ -346,7 +620,7 @@ describe('real Loader composition', () => { const loaded = await loadComposition(0, true) const server = loaded.webServer const body = 'compressible response '.repeat(8) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/text', handler: (_req, res) => { @@ -357,7 +631,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/stream', handler: (_req, res) => { @@ -366,7 +640,7 @@ describe('real Loader composition', () => { res.end(body.slice(40)) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/small', handler: (_req, res) => { @@ -374,7 +648,7 @@ describe('real Loader composition', () => { res.end('small') }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/events', handler: (_req, res) => { @@ -382,7 +656,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/archive', handler: (_req, res) => { @@ -390,7 +664,7 @@ describe('real Loader composition', () => { res.end(body) }, }) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/range', handler: (_req, res) => { @@ -423,7 +697,7 @@ describe('real Loader composition', () => { .headers.get('content-encoding')).toBeNull() // A resource response passes through the same gzip decision as a handler's. - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource-text', resource: () => Promise.resolve(new Response(body, { headers: { 'content-type': 'text/plain; charset=utf-8' } })), @@ -442,7 +716,7 @@ describe('real Loader composition', () => { process.on('warning', onWarning) try { const chunk = new TextEncoder().encode('compressible chunk '.repeat(64 * 1024 / 16)) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource-large', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -480,9 +754,9 @@ describe('real Loader composition', () => { // Routing precedence: exact beats prefix, longest prefix wins, a prefix // route answers its own path, and routes own their method handling // (POST reaches a registered prefix; 405 is fallback-only semantics). - server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) - server.register({ kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } }) - server.register({ kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } }) expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' }) expect(await request(port, '/api/anything')).toMatchObject({ status: 200, body: 'API' }) expect(await request(port, '/api/deep/leaf')).toMatchObject({ status: 200, body: 'DEEP' }) @@ -495,13 +769,13 @@ describe('real Loader composition', () => { expect((await request(port, '/no/such/route')).status).toBe(404) const untap = server.tapIndex(html => html.replace('', '')) expect(server.applyIndexTaps('')).toContain('__T__') - const releaseFallback = server.registerFallback((req, res) => { + const releaseFallback = server.registerFallback({ auth: 'anonymous', handler: (req, res) => { // Decode like a real static server would — a malformed %-escape throws // here, probing the webserver's per-request error containment. decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname) res.writeHead(200, { 'content-type': 'text/html' }) res.end(server.applyIndexTaps('shell')) - }) + } }) expect(() => server.registerFallback(() => {})).toThrow(/fallback already registered/) expect((await request(port, '/no/such/route')).body).toContain('__T__') untap() @@ -515,13 +789,13 @@ describe('real Loader composition', () => { // Duplicate (kind, path) is a misconfiguration and throws; the disposer // restores registrability (register/disposer symmetry). - expect(() => server.register({ kind: 'exact', path: '/probe', handler: () => {} })) + expect(() => server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: () => {} })) .toThrow(/duplicate exact route/) - const disposeOnce = server.register({ kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } }) + const disposeOnce = server.register({ auth: 'anonymous', kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } }) expect(await request(port, '/once')).toMatchObject({ status: 200, body: 'ONCE' }) disposeOnce() expect((await request(port, '/once')).body).toContain('shell') // back to the fallback owner - expect(() => server.register({ kind: 'exact', path: '/once', handler: () => {} })).not.toThrow() + expect(() => server.register({ auth: 'anonymous', kind: 'exact', path: '/once', handler: () => {} })).not.toThrow() // Releasing the seat restores the unclaimed 404 and registrability. releaseFallback() @@ -532,22 +806,22 @@ describe('real Loader composition', () => { // become registrable again after disposal. The accepted socket stays open // so the teardown assertion also covers upgraded-connection ownership. let upgradedServerClosed = false - const disposeUpgrade = server.registerUpgrade({ + const disposeUpgrade = server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: (_req, socket) => { socket.once('close', () => { upgradedServerClosed = true }) socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') }, }) - expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })) + expect(() => server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: () => {} })) .toThrow(/duplicate upgrade route/) const upgraded = await upgrade(port, '/events?stream=mux') disposeUpgrade() - expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })).not.toThrow() + expect(() => server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: () => {} })).not.toThrow() // The webserver contains raw-socket errors even before an upgrade handler // has installed its protocol implementation. - server.registerUpgrade({ + server.registerUpgrade({ auth: 'anonymous', path: '/upgrade-error', handler: async (_req, socket) => { await Promise.resolve() @@ -592,7 +866,7 @@ describe('real Loader composition', () => { cookie: string | null peer: PeerScope | undefined } | undefined - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/resource', resource: (request, peer) => { @@ -627,7 +901,7 @@ describe('real Loader composition', () => { // The status and headers arrive before the first body chunk exists. const firstChunk = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/held', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -646,7 +920,7 @@ describe('real Loader composition', () => { // A streamed body reaches the client chunk by chunk: the first chunk is // readable while the second is still withheld. const second = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/stream', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -668,7 +942,7 @@ describe('real Loader composition', () => { // HEAD writes the status and headers, sends no body, and cancels the body. const headCancelled = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/head', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -681,7 +955,7 @@ describe('real Loader composition', () => { // A client leaving mid-body aborts the request signal and cancels the body. const cancelled = Promise.withResolvers() let endlessSignal: AbortSignal | undefined - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/endless', resource: (request) => { @@ -701,7 +975,7 @@ describe('real Loader composition', () => { // Only GET and HEAD reach a resource; another method is 405 and its body is never read. let posted = false - server.register({ kind: 'exact', path: '/posted', resource: () => { posted = true; return Promise.resolve(new Response('POSTED')) } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/posted', resource: () => { posted = true; return Promise.resolve(new Response('POSTED')) } }) const refused = await request(port, '/posted', { method: 'POST', body: 'payload' }) expect(refused).toMatchObject({ status: 405, body: '' }) expect(refused.headers.get('allow')).toBe('GET, HEAD') @@ -714,7 +988,7 @@ describe('real Loader composition', () => { expect(seen?.url).toBe('http://x/resource?q=2') expect(await rawExchange(port, 'GET /resource?q=3 HTTP/1.1\r\nHost: bad host\r\nConnection: close\r\n\r\n')).toMatch(/^HTTP\/1\.1 201/) expect([seen?.url, seen?.host]).toEqual(['http://x/resource?q=3', 'bad host']) - server.register({ kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) expect((await request(port, '/throws')).status).toBe(400) expect((await request(port, '/resource')).status).toBe(201) }) @@ -727,7 +1001,7 @@ describe('real Loader composition', () => { const server = loaded.webServer const cancelled = Promise.withResolvers() const firstChunk = Promise.withResolvers() - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/tunnel', resource: () => Promise.resolve(new Response(new ReadableStream({ @@ -775,10 +1049,10 @@ describe('real Loader composition', () => { res.writeHead(200) res.end(label) } - server.register({ kind: 'prefix', path: '/assets', resource: resource('assets') }) - server.register({ kind: 'prefix', path: '/assets/deep', resource: resource('deep') }) - server.register({ kind: 'exact', path: '/assets/special', handler: handler('SPECIAL') }) - server.register({ kind: 'prefix', path: '/api', handler: handler('API') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/assets', resource: resource('assets') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/assets/deep', resource: resource('deep') }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/assets/special', handler: handler('SPECIAL') }) + server.register({ auth: 'anonymous', kind: 'prefix', path: '/api', handler: handler('API') }) // Exact, then longest prefix: the same responder HTTP picks answers the // read, and the read passes its Peer to the resource. @@ -802,11 +1076,11 @@ describe('real Loader composition', () => { // The fallback seat answers a read only while it holds a resource. expect((await read('/elsewhere')).status).toBe(404) - const releaseHandler = server.registerFallback(handler('FALLBACK')) + const releaseHandler = server.registerFallback({ auth: 'anonymous', handler: handler('FALLBACK') }) expect((await read('/elsewhere')).status).toBe(404) expect((await request(port, '/elsewhere')).body).toBe('FALLBACK') releaseHandler() - server.registerFallback({ resource: resource('fallback') }) + server.registerFallback({ auth: 'anonymous', resource: resource('fallback') }) const fallback = await read('/elsewhere') expect(await fallback.text()).toBe('fallback:/elsewhere') expect(readersOf.at(-1)).toBe(peer) @@ -819,7 +1093,7 @@ describe('real Loader composition', () => { expect(readersOf).toHaveLength(calls) // A throwing resource rejects the read; over HTTP the same failure is 400. - server.register({ kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/throws', resource: () => Promise.reject(new Error('resource failure')) }) await expect(read('/throws')).rejects.toThrow('resource failure') expect((await request(port, '/throws')).status).toBe(400) }) @@ -897,7 +1171,7 @@ describe('real Loader composition', () => { const server = loaded.webServer expect(server.protocol).toBe('https:') expect(server.getOrigin()).toBe(`https://127.0.0.1:${String(server.port)}`) - server.register({ + server.register({ auth: 'anonymous', kind: 'exact', path: '/tls', handler: (_req, res) => { @@ -923,7 +1197,7 @@ describe('real Loader composition', () => { const server = loaded.webServer expect(server.protocol).toBe('http:') expect(server.getOrigin()).toBe(`http://127.0.0.1:${String(server.port)}`) - server.register({ kind: 'exact', path: '/plain', handler: (_req, res) => { res.writeHead(200); res.end('PLAIN') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/plain', handler: (_req, res) => { res.writeHead(200); res.end('PLAIN') } }) expect(await request(server.port, '/plain')).toMatchObject({ status: 200, body: 'PLAIN' }) await expect(tlsRequest(server.port, '/plain')).rejects.toThrow() }) @@ -994,14 +1268,14 @@ describe('real Loader composition', () => { const loaded = await loadComposition(0, false, '127.0.0.1', { certFile: fixture.certFile, keyFile: fixture.keyFile }) const server = loaded.webServer let upgradeClosed = false - server.registerUpgrade({ + server.registerUpgrade({ auth: 'anonymous', path: '/events', handler: (_req, socket) => { socket.once('close', () => { upgradeClosed = true }) socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n') }, }) - server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) + server.register({ auth: 'anonymous', kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } }) const clients = new Map>() const clientErrors: Error[] = [] diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index da06785281..533a1f5765 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -286,6 +286,8 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | Package | Config | Description | |---|---|---| +| `@deepseek-ai/dsh-host-authentication-desktop` | yes | Desktop private-channel authentication provider | +| `@deepseek-ai/dsh-host-authentication-token` | yes | Default token authentication provider and HTTP cookie exchange | | `@deepseek-ai/dsh-host-directory-picker-auto` | no | Adaptive chooser of the directory-picker seam: resolves the host situation at boot and mounts the native or browse backend for the DeepSeek Harness web GUI host | | `@deepseek-ai/dsh-host-directory-picker-browse` | yes | In-app browsing backend of the directory-picker seam (listing/creation primitives over the host filesystem) | | `@deepseek-ai/dsh-host-directory-picker-native` | no | Native-OS-chooser backend of the directory-picker seam for the DeepSeek Harness web GUI host | diff --git a/packages/session-query/session-log-export/tests/archive.host.spec.ts b/packages/session-query/session-log-export/tests/archive.host.spec.ts index 61791185b3..46ea244bae 100644 --- a/packages/session-query/session-log-export/tests/archive.host.spec.ts +++ b/packages/session-query/session-log-export/tests/archive.host.spec.ts @@ -16,8 +16,7 @@ import type { SessionEvent, SessionHeader, SessionId, ToolResultMessage, UserMes import type { SessionLineageNode } from '@deepseek-ai/dsh-session-query' import { SessionPersistenceNotFoundError } from '@deepseek-ai/dsh-session-persistence' import type { SessionAccess, SessionHandle } from '@deepseek-ai/dsh-session-persistence' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import * as SessionLogExport from '../src/index.ts' declare module '@deepseek-ai/dsh-llm' { @@ -171,7 +170,8 @@ async function buildApi( } as never) } if (services.sessions !== undefined) ctx.provide('sessions', services.sessions as never) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin(SessionLogExport, { ...services.compressionLevel === undefined ? {} diff --git a/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts b/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts index 86f15828fe..29e21fae67 100644 --- a/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts +++ b/packages/session-query/session-log-export/tests/markdown-route.host.spec.ts @@ -1,6 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import type { MessageId } from '@deepseek-ai/dsh-llm' import type { SessionEvent, SessionHeader, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' @@ -89,7 +88,8 @@ async function mounted( ctx.provide('commands', { register: () => () => {} } as never) if (sessionQuery !== undefined) ctx.provide('sessionQuery', sessionQuery as never) if (persistence !== undefined) ctx.provide('sessionPersistence', persistence as SessionPersistence) - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber return { diff --git a/packages/session-query/session-log-export/tests/route.host.spec.ts b/packages/session-query/session-log-export/tests/route.host.spec.ts index 5d793aec0e..eeff55888d 100644 --- a/packages/session-query/session-log-export/tests/route.host.spec.ts +++ b/packages/session-query/session-log-export/tests/route.host.spec.ts @@ -1,6 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import { HostConnectionService } from '@deepseek-ai/dsh-client-connection' -import type { BrowserAuth } from '@deepseek-ai/dsh-client-connection/src/browser-auth.ts' +import { ConnectionAuthentication, HostConnectionService } from '@deepseek-ai/dsh-client-connection' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence' @@ -52,7 +51,8 @@ async function mounted(withServices: boolean): Promise<{ readImage: async () => { throw new Error('fixture has no images') }, } as never) } - const connection = new HostConnectionService(ctx, [], {} as BrowserAuth) + new ConnectionAuthentication(ctx) + const connection = new HostConnectionService(ctx, []) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber return { connection, dispose: () => fiber.dispose() } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a21a45066..0d91895e89 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -755,6 +755,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../packages/client/connection '@deepseek-ai/dsh-client-product-analytics': specifier: workspace:* version: link:../../packages/client/product-analytics @@ -785,6 +788,12 @@ importers: '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths + '@deepseek-ai/dsh-host-authentication-desktop': + specifier: workspace:* + version: link:../../packages/host/authentication-desktop + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../../packages/host/webserver '@deepseek-ai/dsh-official-bundles': specifier: workspace:* version: link:../../packages/util/official-bundles @@ -881,6 +890,9 @@ importers: '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* version: link:../../packages/credentials/deepseek-account + '@deepseek-ai/dsh-host-authentication-desktop': + specifier: workspace:* + version: link:../../packages/host/authentication-desktop '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../packages/host/webserver @@ -900,6 +912,12 @@ importers: specifier: 3.1.1 version: 3.1.1 devDependencies: + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../packages/api/gateway + '@deepseek-ai/dsh-api-remote-access': + specifier: workspace:* + version: link:../../packages/api/remote-access '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand @@ -918,9 +936,18 @@ importers: '@deepseek-ai/dsh-session-persistence': specifier: workspace:* version: link:../../packages/session/session-persistence + '@deepseek-ai/dsh-typert-registry': + specifier: workspace:* + version: link:../../packages/typert/registry '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../packages/util/workspace-path + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 + ws: + specifier: ^8.21.3 + version: 8.21.3 apps/desktop-publisher: dependencies: @@ -3253,6 +3280,9 @@ importers: '@deepseek-ai/dsh-harness-dev-context': specifier: workspace:* version: link:../../context/harness-dev-context + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../../host/authentication-token '@deepseek-ai/dsh-host-directory-picker-auto': specifier: workspace:* version: link:../../host/directory-picker-auto @@ -3494,9 +3524,6 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand - '@deepseek-ai/dsh-credentials': - specifier: workspace:* - version: link:../../credentials/credentials '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery @@ -3510,6 +3537,12 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:* version: link:../../attachment/attachment + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../../host/authentication-token '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver @@ -8472,6 +8505,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../credentials @@ -13357,6 +13393,52 @@ importers: specifier: workspace:* version: link:../../core/tools + packages/host/authentication-desktop: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + + packages/host/authentication-token: + dependencies: + '@deepseek-ai/dsh-credentials': + specifier: workspace:* + version: link:../../credentials/credentials + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/dsh-client-connection': + specifier: workspace:* + version: link:../../client/connection + '@deepseek-ai/dsh-credentials-local': + specifier: workspace:* + version: link:../../credentials/credentials-local + '@deepseek-ai/dsh-host-frontend-static': + specifier: workspace:* + version: link:../frontend-static + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + packages/host/directory-picker: devDependencies: '@deepseek-ai/cordis': @@ -13450,6 +13532,9 @@ importers: '@deepseek-ai/dsh-credentials-local': specifier: workspace:* version: link:../../credentials/credentials-local + '@deepseek-ai/dsh-host-authentication-token': + specifier: workspace:* + version: link:../authentication-token '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../webserver @@ -13478,6 +13563,9 @@ importers: '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../webserver + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol packages/host/plugin-inventory: dependencies: diff --git a/scripts/cordis-walk.ts b/scripts/cordis-walk.ts index 3a38f0ca29..80aeed6f34 100644 --- a/scripts/cordis-walk.ts +++ b/scripts/cordis-walk.ts @@ -72,7 +72,8 @@ export function contextKeyMap(body: ts.ModuleBlock, sf: ts.SourceFile): Map { expect(events).toEqual(['second/changed']) }) - it('reads string-literal and identifier member names from an Events merge', () => { + it('reads string-literal and identifier service and event names', () => { const sf = ts.createSourceFile('x.ts', [ "declare module '@deepseek-ai/cordis' {", ' interface Events {', @@ -196,6 +196,8 @@ describe('cordis-walk scan reach', () => { ' }', ' interface Context {', ' thing: ThingService', + " 'connection.authentication': AuthenticationService", + ' "connection.other": OtherService', ' }', '}', '', @@ -206,6 +208,10 @@ describe('cordis-walk scan reach', () => { : null if (!body) throw new Error('fixture did not parse to a module block') expect(eventNameList(body, sf)).toEqual(['scope/list', 'plain']) - expect([...contextKeyMap(body, sf)]).toEqual([['thing', 'ThingService']]) + expect([...contextKeyMap(body, sf)]).toEqual([ + ['thing', 'ThingService'], + ['connection.authentication', 'AuthenticationService'], + ['connection.other', 'OtherService'], + ]) }) }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 5c3da61024..90526d7a80 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -59,6 +59,7 @@ export const SERVICE_PAGE: Record = { productTelemetry: 'product-telemetry.md', productAnalytics: 'product-telemetry.md', connection: 'web-server.md', + 'connection.authentication': 'web-server.md', pluginManager: 'boot.md', actionCards: 'boot.md', pluginRecommendations: 'boot.md', @@ -313,6 +314,8 @@ export const EVENT_WALK_EXEMPTIONS: Record = { * appear on more than one page. */ export const LINK_MAP: Readonly> = { + AuthenticationProvider: '../../packages/client/connection/README.md#browser-authentication-and-request-trust', + PeerId: 'typert.md', Principal: 'typert.md', PrincipalMap: 'typert.md', RemoteAccessResource: 'typert.md', @@ -947,6 +950,12 @@ export const LINK_MAP: Readonly> = { PermissionCatalog: 'permission-presets.md', PresetOption: 'permission-presets.md', PresetSpec: 'permission-presets.md', + WebEntryUrl: 'web-server.md', + WebAdmission: 'web-server.md', + WebAuthPolicy: 'web-server.md', + WebAuthRequest: 'web-server.md', + WebAuthenticationRule: 'web-server.md', + WebFallback: 'web-server.md', WebRoute: 'web-server.md', WebResourceRoute: 'web-server.md', IndexInjection: 'web-server.md', @@ -1008,6 +1017,7 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ 'Plugin', 'AbortSignal', 'Headers', + 'URL', 'AsyncIterable', 'Context', 'Error', @@ -1028,6 +1038,8 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ 'ReadonlySet', 'Request', 'Response', + 'Buffer', + 'Duplex', 'IncomingMessage', 'ServerResponse', 'ReturnType', @@ -1043,18 +1055,14 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { RecommendationDetails: 'packages/experimental/plugin-recommendations/README.md', ProductEvent: 'Desktop event fields are owned by packages/client/product-analytics/README.md and src/events.ts', ConnectionFetchHandler: 'shared Fetch dispatch is owned by packages/client/connection/src/rpc.ts', - ConnectionRequestRejection: 'transport rejection status is owned by packages/client/connection/src/rpc.ts', ConnectionTrustRequest: 'transport authentication input is owned by packages/client/connection/src/rpc.ts', PeerAdmission: 'Peer admission outcome is owned by packages/client/connection/src/rpc.ts', - ConnectionAdmission: 'physical socket admission and release are owned by packages/client/connection/src/rpc.ts', PeerScope: 'Peer scope contract is owned by packages/typert/protocol/src/types.ts', RemoteAccessPolicy: 'access policy contract is owned by packages/api/remote-access/README.md', RemoteAccessRequest: 'Gateway decision requests are owned by packages/api/remote-access/README.md', RemoteAccessDecision: 'Gateway decisions are owned by packages/api/remote-access/README.md', RemoteAccessFrame: 'access snapshot frames are owned by packages/api/remote-access/README.md', RemoteAccessBaseline: 'access snapshot frames are owned by packages/api/remote-access/README.md', - ConnectionIndexRequest: 'frontend authentication request is owned by packages/client/connection/src/rpc.ts', - ConnectionIndexResponse: 'frontend authentication response is owned by packages/client/connection/src/rpc.ts', Profile: 'resolved profile layers are owned by packages/boot/app-boot/README.md', PatchOptions: 'Include patch entries are owned by vendor/include (vendored upstream)', McpResourceProvider: 'scoped resource provider is owned by packages/mcp/mcp-resources/README.md', diff --git a/scripts/gen-doc-graphs.spec.ts b/scripts/gen-doc-graphs.spec.ts index 3274c79f12..9315e03b92 100644 --- a/scripts/gen-doc-graphs.spec.ts +++ b/scripts/gen-doc-graphs.spec.ts @@ -27,7 +27,15 @@ const FIXTURE: Record = { }, include: ['vendor/**/*.ts', 'packages/**/*.ts'], }), - 'vendor/cordis/src/context.ts': 'export class Context { private brand!: void }\n', + 'vendor/cordis/src/context.ts': [ + 'export class Context {', + ' private brand!: void', + ' bail(...args: unknown[]): void {}', + ' on(...args: unknown[]): void {}', + ' once(...args: unknown[]): void {}', + '}', + '', + ].join('\n'), 'vendor/cordis/src/events.ts': [ 'export class EventsService {', ' dispatch(type: string, args: unknown[]): unknown[] { return [type, args] }', @@ -63,6 +71,28 @@ const FIXTURE: Record = { 'packages/fix/pkgc/src/helper.ts': "function scriptFire(args: [string]): void { void gEvents.dispatch('emit', args) }\n", 'packages/fix/pkgc/src/caller.ts': "scriptFire(['pkgc/script-event'])\n", + 'packages/fix/bailtypes/src/receiver.ts': [ + "import { Context } from '../../../../vendor/cordis/src/context.ts'", + 'export declare const application: Context', + "export declare const event: 'bail/union-a' | 'bail/union-b'", + '', + ].join('\n'), + 'packages/fix/bailcalls/src/index.ts': [ + "import { application as receiver, event } from '../../bailtypes/src/receiver.ts'", + "receiver.bail('bail/direct')", + "receiver.bail({}, 'bail/scoped')", + 'receiver.bail(event)', + "receiver.on('bail/direct', () => {})", + "receiver.once('bail/scoped', () => {})", + 'declare const widened: string', + 'receiver.bail(widened)', + 'const ctx = { bail(...args: unknown[]): void {} }', + "ctx.bail('bail/unrelated')", + '// An untyped receiver cannot establish event API ownership.', + 'declare const untyped: any', + "untyped.bail('bail/untyped')", + '', + ].join('\n'), } const root = mkdtempSync(join(tmpdir(), 'gen-doc-graphs-')) @@ -99,6 +129,34 @@ describe('event relation call-site indexing', () => { }) }) +describe('type-aware bail dispatch', () => { + function collectBailRelations() { + return new EventRelationCollector(project, sources.filter(source => source.pkg === 'bailcalls')).collect() + } + + it.each(['bail/direct', 'bail/scoped', 'bail/union-a', 'bail/union-b'])( + 'records %s from an imported Context receiver as a bail dispatcher', + (event) => { + expect(collectBailRelations().get(event)?.dispatchers).toEqual(new Map([ + ['bailcalls', new Set(['bail'])], + ])) + }, + ) + + it('keeps on and once registrations as listeners', () => { + const relations = collectBailRelations() + expect(relations.get('bail/direct')?.listeners).toEqual(new Set(['bailcalls'])) + expect(relations.get('bail/scoped')?.listeners).toEqual(new Set(['bailcalls'])) + expect(relations.get('bail/union-a')?.listeners.size).toBe(0) + }) + + it('excludes unrelated and untyped receivers and widened event names', () => { + expect([...collectBailRelations().keys()].sort()).toEqual([ + 'bail/direct', 'bail/scoped', 'bail/union-a', 'bail/union-b', + ]) + }) +}) + describe('memoized filesystem probes', () => { function countingSystem(): { system: ts.System; calls: string[] } { const calls: string[] = [] diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 01d33a95e9..7078d12753 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -192,7 +192,16 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Authenticated browser transport', mode: 'core', consumers: ['api-gateway', 'host-frontend-static'], - note: 'Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams.', + note: 'Applies source policy and shared HTTP request dispatch; credential verification belongs to ConnectionAuthentication, and API adapters register endpoints and streams.', + }, + { + key: 'connection.authentication', + pkg: 'client-connection', + title: 'Connection authentication provider registry', + mode: 'seam', + implementations: ['host-authentication-token', 'host-authentication-desktop'], + consumers: ['client-connection'], + note: 'Tries scope-owned credential verifiers in registration order and returns the first live Peer; transport source policy and business authorization stay with their consumers.', }, { key: 'forge', @@ -1178,7 +1187,7 @@ type CallSiteIndex = Map> = { + 'packages/host/authentication-desktop': { category: 'optional', reason: 'Mounted by the private Desktop Host with its parent-process credential, outside default Web profiles.' }, 'packages/core/agent-tool-presentation': { category: 'optional', reason: 'Deprecated selector retained for existing executor configurations.' }, 'packages/browser-use/browser-use': { category: 'optional', reason: 'Service definition used by explicitly selected browser providers.' }, 'packages/computer-use/computer-use': { category: 'optional', reason: 'Service definition used by explicitly selected computer providers.' }, diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 2a19069258..6a626d8973 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -69,6 +69,8 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/experimental/voice-input-bundle': { kind: 'none', reason: 'Composes dictation and preparation plugins without adding any model-facing contribution.' }, 'packages/telemetry/otel': { kind: 'none', reason: 'The service delivers caller-selected records without changing model context.' }, 'packages/host/product-telemetry-otel': { kind: 'none', reason: 'The plugin exports explicit analytics records without contributing model context.' }, + 'packages/host/authentication-token': { kind: 'none', reason: 'Launch-token exchange and Cookie verification authenticate HTTP callers without contributing model input.' }, + 'packages/host/authentication-desktop': { kind: 'none', reason: 'Private Desktop credential verification authenticates HTTP callers without contributing model input.' }, 'packages/api/terminal-controller': { kind: 'indirect', reason: 'Working-directory recovery owns directory context; user terminal screens never enter model requests.' }, 'packages/client/ui-sidebar-terminal': { kind: 'none', reason: 'The browser renders user terminal screens without exposing them to the model.' }, 'packages/ssh/ssh-helper-runtime': { kind: 'none', reason: 'The private executable carrier registers no model-facing content; its providers and consumers own operation results.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index d14d434d5c..f7e5269ec6 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -251,6 +251,10 @@ "@deepseek-ai/dsh-host-open-in-app/shared": ["./packages/host/open-in-app/src/shared.ts"], "@deepseek-ai/dsh-host-webserver": ["./packages/host/webserver/src"], "@deepseek-ai/dsh-host-frontend-static": ["./packages/host/frontend-static/src"], + "@deepseek-ai/dsh-host-authentication-desktop": ["./packages/host/authentication-desktop/src/index.ts"], + "@deepseek-ai/dsh-host-authentication-desktop/src/*": ["./packages/host/authentication-desktop/src/*"], + "@deepseek-ai/dsh-host-authentication-token": ["./packages/host/authentication-token/src/index.ts"], + "@deepseek-ai/dsh-host-authentication-token/src/*": ["./packages/host/authentication-token/src/*"], "@deepseek-ai/dsh-plugin-manager": ["./packages/boot/plugin-manager/src"], "@deepseek-ai/dsh-plugin-manager/diagnostic": ["./packages/boot/plugin-manager/src/diagnostic.ts"], "@deepseek-ai/dsh-plugin-manager/types": ["./packages/boot/plugin-manager/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index d77b87c35e..faa4315244 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -597,6 +597,8 @@ { "path": "./packages/host/directory-picker-browse" }, { "path": "./packages/host/directory-picker-native" }, { "path": "./packages/host/frontend-static" }, + { "path": "./packages/host/authentication-token" }, + { "path": "./packages/host/authentication-desktop" }, { "path": "./packages/host/open-in-app" }, { "path": "./packages/host/plugin-inventory" }, { "path": "./packages/boot/plugin-manager" },