refactor(connection): add connection auth provider for remote connection (#8266)
* refactor(connection): extract peer authentication providers * test(connection): cover provider lifecycle and satisfy package gates * fix(packaging): publish authentication provider locale resources * test(auth): use runtime login output and cover gateway admission * fix(auth): preserve Worker requests and migrate Desktop fixtures * refactor(auth): centralize route admission with required policy * fix(release): align authentication providers with rc.2 * refactor(connection): keep peer lookup and source policy private * test(gateway): cover centralized upgrade rejections * fix(ci): authenticate homepage compression probe * refactor(auth): let Token own API socket lifecycle * fix(auth): prevent caching admission refusals and clarify ownership * refactor(web): collect provider entry URLs after readiness * refactor(webserver): name the shared entry URL event * refactor(connection): provide authentication as a nested service * fix(web-app): restore startup publication defaults * fix(auth): scope web events and preserve callback flows * docs(auth): record the implemented provider architecture * fix(auth): require owner access for administrative routes
This commit is contained in:
1 parent
98606fa09b
commit
71753fdf91
188 files changed
+6448
-1886
No files matched your search
+6
-6
@@ -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
|
||||
@@ -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.
|
||||
|
||||
|
||||
+6
-6
@@ -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 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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 上限限制累计量 |
|
||||
|
||||
+4
-4
@@ -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
|
||||
+2
-2
@@ -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=<launch-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=<launch-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.
|
||||
+2
-2
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
浏览器保留现有签名 Cookie、根路径 launch token 交换、共享 `connection.browserPeer` 和恢复行为。只有 API 调用方通过 `GET /connect?token=<launch-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=<launch-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 中间件的实现位置,不取代本协议与生命周期决策。
|
||||
+37
@@ -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
|
||||
+141
@@ -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.
|
||||
+141
@@ -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 产品。
|
||||
+34
@@ -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
|
||||
@@ -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.
|
||||
+85
@@ -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)记录中的实现归属。原记录继续保留凭据、生命周期和安全规则的独立理由,没有任何一份被完全取代或归档。
|
||||
@@ -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<number | null>(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<string, string> }
|
||||
}>((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<string, string> } })
|
||||
}
|
||||
})
|
||||
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<void>((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])
|
||||
|
||||
@@ -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<typeof fixture>, 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')
|
||||
|
||||
@@ -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:*",
|
||||
|
||||
@@ -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<string>
|
||||
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<string>()
|
||||
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')) },
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
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<void> => 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<void> {
|
||||
updateTasks?: ReturnType<typeof installDesktopUpdateTaskControl>
|
||||
quitInspection?: ReturnType<typeof installDesktopQuitInspection>
|
||||
} = {}
|
||||
const send = (message: object): Promise<void> => 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<void> => stopping ??= (async () => {
|
||||
for (const abort of dragReads.values()) abort.abort()
|
||||
await Promise.allSettled(dragTasks)
|
||||
@@ -124,16 +139,33 @@ async function main(): Promise<void> {
|
||||
}
|
||||
})().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) {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
@@ -8,6 +8,7 @@
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{ "path": "../../packages/host/authentication-desktop" },
|
||||
{ "path": "../../vendor/cordis" },
|
||||
{ "path": "../../packages/core/agent" },
|
||||
{ "path": "../../packages/jobs/jobs" },
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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. |
|
||||
|
||||
|
||||
@@ -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 发布。 |
|
||||
|
||||
|
||||
@@ -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:*",
|
||||
|
||||
@@ -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('<html')) {
|
||||
throw new Error('desktop runtime: packaged frontend smoke failed')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Electron Node-mode child lifecycle for the shared Web application. */
|
||||
|
||||
import { spawn, type ChildProcess } from 'node:child_process'
|
||||
import { DesktopParentAuthentication } from './parent-authentication.ts'
|
||||
import { join } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account'
|
||||
@@ -61,6 +62,18 @@ export const QUIT_INSPECTION_DEADLINE_MS = 2_000
|
||||
const MAX_HOST_DIAGNOSTIC_CHARS = 64 * 1024
|
||||
const runIdSchema = z.uuid()
|
||||
|
||||
function isOwnedHostUrl(value: unknown): value is string {
|
||||
if (typeof value !== 'string') return false
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return (url.protocol === 'http:' || url.protocol === 'https:')
|
||||
&& url.hostname === '127.0.0.1' && url.username === '' && url.password === ''
|
||||
&& url.pathname === '/' && url.search === '' && url.hash === ''
|
||||
} catch (_invalidUrl) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isDesktopHostEvent(message: unknown): message is DesktopHostEvent {
|
||||
if (typeof message !== 'object' || message === null || !('type' in message)) return false
|
||||
const candidate = message as Record<string, unknown>
|
||||
@@ -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<void>, milliseconds: number): Promise<b
|
||||
}
|
||||
}
|
||||
|
||||
/** Browser authentication URL reported by the running Web application. */
|
||||
/** Host readiness plus the parent-owned credential used only by the main process. */
|
||||
export interface DesktopHostReady {
|
||||
readonly url: string
|
||||
readonly injections?: readonly unknown[] | undefined
|
||||
/** Cookie header for the owned Host; synthesized locally and never received from the renderer. */
|
||||
readonly authenticationCookie: string
|
||||
}
|
||||
|
||||
/** The child has exited, but task teardown did not finish successfully. */
|
||||
@@ -156,6 +171,7 @@ export class DesktopHostFatalError extends Error {
|
||||
|
||||
/** One Web backend running under the Electron executable in Node mode. */
|
||||
export class DesktopHostProcess {
|
||||
readonly #authentication = new DesktopParentAuthentication()
|
||||
private runId: PluginOperationRunId | undefined
|
||||
private child: ChildProcess | undefined
|
||||
private readyResolve!: (ready: DesktopHostReady) => 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
|
||||
|
||||
@@ -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
|
||||
@@ -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<void> {
|
||||
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)
|
||||
|
||||
@@ -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<void> | 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<ChildProcess, 'send'>): Promise<void> {
|
||||
return this.#delivery ??= new Promise<void>((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<string> {
|
||||
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}`
|
||||
}
|
||||
}
|
||||
@@ -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<string> {
|
||||
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<readonly { readonly name: string }[]>
|
||||
@@ -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<Response> {
|
||||
|
||||
@@ -39,7 +39,7 @@ function record(value: unknown): value is Record<string, unknown> {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@@ -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<typeof import('node:child_process')>()
|
||||
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<Error>()
|
||||
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:[email protected]: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<typeof import('node:child_process')>('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([
|
||||
|
||||
@@ -23,7 +23,7 @@ const fileDrag = vi.hoisted(() => ({ dispose: vi.fn<() => Promise<void>>(), 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<string, string> },
|
||||
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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<typeof import('node:child_process')>(),
|
||||
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('<html>packaged fixture</html>')
|
||||
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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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<void>>().mockResolvedValue(undefined),
|
||||
loadWorkspace: vi.fn<(url: string) => Promise<void>>().mockResolvedValue(undefined),
|
||||
showWorkspace: vi.fn(),
|
||||
|
||||
@@ -93,7 +93,7 @@ async function mockPlatform() {
|
||||
await new Promise<void>((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<void>((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')
|
||||
|
||||
@@ -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<Page> {
|
||||
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: {
|
||||
|
||||
@@ -651,11 +651,11 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
|
||||
},
|
||||
},
|
||||
// The bundle's web-runtime row resolves the same built dist under test
|
||||
// (apps/web IS @deepseek-ai/dsh-web-frontend); native browser opening and the
|
||||
// URL line are disabled because this scaffold owns its Playwright browser.
|
||||
// (apps/web IS @deepseek-ai/dsh-web-frontend). The scaffold captures the real
|
||||
// WebApp-published login URL; Playwright owns browser opening.
|
||||
// Preserve the composed surface-context choice because a patch replaces
|
||||
// the row's complete config.
|
||||
{ id: 'web-runtime', config: { openBrowser: false, printUrl: false, surfaceContext } },
|
||||
{ id: 'web-runtime', config: { surfaceContext, openBrowser: false, printUrl: true } },
|
||||
...publicHost === undefined && options.remoteAuthority === undefined
|
||||
? []
|
||||
: [{
|
||||
@@ -844,9 +844,37 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
|
||||
resolution,
|
||||
})
|
||||
await ctx.plugin(Loader)
|
||||
await mountRootInclude(ctx, rootConfig, readProfilePatches('dsh', profileContext))
|
||||
await ctx.loader.await()
|
||||
await auditStartupEntries(ctx, 'web e2e scaffold')
|
||||
// Scaffold boots already own process.cwd() exclusively within their test worker.
|
||||
// Capture only this listener's login line, and restore console on failed boot too.
|
||||
const startupLogin = Promise.withResolvers<URL>()
|
||||
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<typeof setTimeout> | 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<We
|
||||
publicProxy.setTarget(port)
|
||||
baseUrl = `http://${publicHost}:${String(publicProxy.port)}${publicPrefix}`
|
||||
}
|
||||
authenticatedUrl = ctx.connection.authenticatedUrl(baseUrl)
|
||||
const browserLoginUrl = new URL(baseUrl)
|
||||
browserLoginUrl.search = startupLoginUrl.search
|
||||
authenticatedUrl = browserLoginUrl.href
|
||||
// Chromium resolves *.localhost itself; Node may not. Both scaffold
|
||||
// listeners bind loopback, including the optional prefix proxy.
|
||||
const loginUrl = new URL(authenticatedUrl)
|
||||
|
||||
@@ -537,9 +537,11 @@ it('assembles the shipped Web transport, catalog, guidance, and defaults', async
|
||||
const ctx = scaffold.ctx
|
||||
expect(ctx.llm.listProviders().some(provider => 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()
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
en: 41d772192075e133
|
||||
zh: 5ef3da69b4de1d8a
|
||||
/capability-seams-and-core-services:
|
||||
en: 78778294644e7b42
|
||||
zh: 2985cca0ffc69256
|
||||
en: 3dd4fb581635c873
|
||||
zh: 40647337f0ea2a02
|
||||
@@ -36,6 +36,9 @@ flowchart LR
|
||||
svc_connection["ctx.connection<br/>Authenticated browser transport"]
|
||||
pkg_api_gateway["api-gateway"]
|
||||
pkg_host_frontend_static["host-frontend-static"]
|
||||
svc_connection_authentication["ctx.connection.authentication<br/>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<br/>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. |
|
||||
|
||||
@@ -38,6 +38,9 @@ flowchart LR
|
||||
svc_connection["ctx.connection<br/>Authenticated browser transport"]
|
||||
pkg_api_gateway["api-gateway"]
|
||||
pkg_host_frontend_static["host-frontend-static"]
|
||||
svc_connection_authentication["ctx.connection.authentication<br/>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<br/>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 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 |
|
||||
|
||||
+40
-9
@@ -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 {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-hooks-codex -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-desktop -->
|
||||
<a id="deepseek-aidsh-host-authentication-desktop"></a>
|
||||
|
||||
## `@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
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-desktop -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-token -->
|
||||
<a id="deepseek-aidsh-host-authentication-token"></a>
|
||||
|
||||
## `@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
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-token -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-host-directory-picker-browse -->
|
||||
<a id="deepseek-aidsh-host-directory-picker-browse"></a>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-hooks-codex -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-desktop -->
|
||||
<a id="deepseek-aidsh-host-authentication-desktop"></a>
|
||||
|
||||
## `@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
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-desktop -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-token -->
|
||||
<a id="deepseek-aidsh-host-authentication-token"></a>
|
||||
|
||||
## `@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
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-host-authentication-token -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-host-directory-picker-browse -->
|
||||
<a id="deepseek-aidsh-host-directory-picker-browse"></a>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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`) | - |
|
||||
|
||||
@@ -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`) | - |
|
||||
|
||||
@@ -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) |
|
||||
|
||||
@@ -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) |
|
||||
|
||||
@@ -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
|
||||
+130
-47
@@ -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<void>
|
||||
handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise<void>
|
||||
/** 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<Response>
|
||||
@@ -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.
|
||||
|
||||
<a id="config"></a>
|
||||
|
||||
@@ -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).
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
@@ -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)
|
||||
|
||||
<a id="ctxconnectionauthentication--connectionauthentication"></a>
|
||||
|
||||
### `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<void>
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
<a id="ctxwebapp--webapp"></a>
|
||||
|
||||
### `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<WebResourceRoute, 'resource'>): () => 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<WebResourceRoute, 'resourc
|
||||
* 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;
|
||||
@@ -324,6 +331,42 @@ Source: [`packages/client/connection/src/index.ts`](../../packages/client/connec
|
||||
|
||||
### `webserver/*` events
|
||||
|
||||
<a id="webserverauthorize--bail"></a>
|
||||
|
||||
#### `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)
|
||||
|
||||
<a id="webserverentry-url--emit"></a>
|
||||
|
||||
#### `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)
|
||||
|
||||
<a id="webserverindex-inject--emit"></a>
|
||||
|
||||
#### `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)
|
||||
|
||||
<a id="webserverrequest--waterfall"></a>
|
||||
|
||||
#### `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<void>): Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts)
|
||||
|
||||
<a id="webserverupgrade--waterfall"></a>
|
||||
|
||||
#### `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<void>, ): Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -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<void>
|
||||
handler: (req: IncomingMessage, res: ServerResponse, peer?: PeerScope) => void | Promise<void>
|
||||
/** 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<Response>
|
||||
@@ -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。
|
||||
|
||||
<a id="config"></a>
|
||||
|
||||
@@ -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) 中。
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
@@ -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)
|
||||
|
||||
<a id="ctxconnectionauthentication--connectionauthentication"></a>
|
||||
|
||||
### `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<void>
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
<a id="ctxwebapp--webapp"></a>
|
||||
|
||||
### `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<WebResourceRoute, 'resource'>): () => 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<WebResourceRoute, 'resourc
|
||||
* 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;
|
||||
@@ -324,6 +331,42 @@ Source: [`packages/client/connection/src/index.ts`](../../packages/client/connec
|
||||
|
||||
### `webserver/*` events
|
||||
|
||||
<a id="webserverauthorize--bail"></a>
|
||||
|
||||
#### `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)
|
||||
|
||||
<a id="webserverentry-url--emit"></a>
|
||||
|
||||
#### `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)
|
||||
|
||||
<a id="webserverindex-inject--emit"></a>
|
||||
|
||||
#### `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)
|
||||
|
||||
<a id="webserverrequest--waterfall"></a>
|
||||
|
||||
#### `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<void>): Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts)
|
||||
|
||||
<a id="webserverupgrade--waterfall"></a>
|
||||
|
||||
#### `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<void>, ): Promise<void>
|
||||
```
|
||||
|
||||
Source: [`packages/host/webserver/src/index.ts`](../../packages/host/webserver/src/index.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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。
|
||||
@@ -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<Promise<void>>()
|
||||
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)
|
||||
|
||||
@@ -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'))
|
||||
}
|
||||
@@ -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<void>; 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<string, PeerScope>()
|
||||
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<number> => {
|
||||
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<WebSocket> => {
|
||||
const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, { headers: { cookie } })
|
||||
const closed = new Promise<void>((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([])
|
||||
})
|
||||
@@ -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<Context, string>()
|
||||
|
||||
@@ -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<string> {
|
||||
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<Record<string, string>>) { 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
|
||||
}
|
||||
@@ -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[] = []
|
||||
|
||||
@@ -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<string, unknown>[] = []
|
||||
@@ -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<string, unknown>[] = []
|
||||
@@ -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<string, unknown>[] = []
|
||||
@@ -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<string, unknown>[] = []
|
||||
@@ -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<string, unknown>[] = []
|
||||
@@ -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<typeof randomUUID>
|
||||
const secondId = '00000000-0000-4000-8000-000000000012' as ReturnType<typeof randomUUID>
|
||||
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<string, unknown>[] = []
|
||||
@@ -1685,7 +1703,7 @@ async function setup(
|
||||
|
||||
async function acceptsSocket(ctx: Context): Promise<boolean> {
|
||||
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<void>((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<RemoteEventTestClient> {
|
||||
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 },
|
||||
})
|
||||
|
||||
@@ -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<WebServer, 'register' | 'tapIndex' | 'port'> {
|
||||
@@ -165,9 +162,18 @@ function fakeHttpServer(routes: WebRoute[]): Pick<WebServer, 'register' | 'tapIn
|
||||
}
|
||||
}
|
||||
|
||||
async function serveRoute(route: WebRoute): Promise<{ readonly origin: string; close(): Promise<void> }> {
|
||||
async function serveRoute(ctx: Context, route: WebRoute): Promise<{ readonly origin: string; close(): Promise<void> }> {
|
||||
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<void>(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<string> {
|
||||
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<Record<string, string>>) { 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`, {
|
||||
|
||||
@@ -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<void>((resolve, reject) => {
|
||||
inspector.close((error) => {
|
||||
if (error) reject(error)
|
||||
else resolve()
|
||||
})
|
||||
}), 'fixture: non-mux WebSocket server')
|
||||
const peers: Array<Connection.PeerScope | undefined> = []
|
||||
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<IncomingMessage>((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<void>((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<Duplex>()
|
||||
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<undefined>()
|
||||
const resume = Promise.withResolvers<undefined>()
|
||||
const cleaned = Promise.withResolvers<undefined>()
|
||||
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<undefined>()
|
||||
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<undefined>()
|
||||
const resume = Promise.withResolvers<undefined>()
|
||||
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<Host> {
|
||||
{ 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<Host> {
|
||||
'@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<Host> {
|
||||
}
|
||||
|
||||
async function exchange(host: Host, mode: 'html' | 'none' | 'answer'): Promise<string> {
|
||||
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<s
|
||||
return cookie.split(';', 1)[0]!
|
||||
}
|
||||
|
||||
function socketClient(host: Host, cookie: string): SocketClient {
|
||||
const socket = new WebSocket(`${host.origin.replace('http:', 'ws:')}/api/remote.mux`, { headers: { cookie } })
|
||||
function socketClient(host: Host, cookie: string, path = '/api/remote.mux'): SocketClient {
|
||||
const socket = new WebSocket(`${host.origin.replace('http:', 'ws:')}${path}`, { headers: { cookie } })
|
||||
const closed = new Promise<void>((resolve) => { socket.once('close', () => { resolve() }) })
|
||||
const frames: RemoteStreamServerMessage[] = []
|
||||
const errors: Error[] = []
|
||||
|
||||
@@ -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('<body>shell</body>')
|
||||
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,
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
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/<id>.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/<id>.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 |
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -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-
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
此 bundle 由一层五个文件的补丁和一个运行时胶水插件组成:`cordis.patch.yml` 承载宿主行和 preset 注册表,每个 `presets/<id>.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/<id>.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) | 页面可达后的默认浏览器交接 |
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:*",
|
||||
|
||||
@@ -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<void> {
|
||||
async function openBrowser(url: string, signal?: AbortSignal): Promise<void> {
|
||||
signal?.throwIfAborted()
|
||||
const launcher = spawnBrowserLauncher(url)
|
||||
let launcherStderr = ''
|
||||
launcher.stderr?.setEncoding('utf8')
|
||||
launcher.stderr?.on('data', (chunk: string) => { launcherStderr += chunk })
|
||||
await new Promise<void>((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<void> {
|
||||
}
|
||||
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<void>
|
||||
openBrowser: (url: string, signal?: AbortSignal) => Promise<void>
|
||||
} = { 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<void> | 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.
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<typeof import('node:child_process')>(), spawn: vi.fn(),
|
||||
}))
|
||||
afterEach(() => { vi.restoreAllMocks(); vi.mocked(spawn).mockReset(); vi.unstubAllEnvs() })
|
||||
|
||||
type BrowserLauncher = ChildProcess & { stderr: PassThrough; kill: ReturnType<typeof vi.fn<() => 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
|
||||
})
|
||||
@@ -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, '<!doctype html><head></head><body>token-startup-ready</body>')
|
||||
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)
|
||||
})
|
||||
@@ -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, '<!doctype html><title>ready</title>')
|
||||
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<void>((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)
|
||||
})
|
||||
})
|
||||
@@ -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<void>((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()
|
||||
})
|
||||
@@ -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<void> } = {}) {
|
||||
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<WebServer, 'host' | 'protocol' | 'registerFallback'> = {
|
||||
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<void>>().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<Config, 'printUrl' | 'openBrowser'>, 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<undefined>()
|
||||
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<undefined>()
|
||||
const audited = Promise.withResolvers<undefined>()
|
||||
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<undefined>()
|
||||
const open = vi.fn<typeof internals.openBrowser>(() => handoff.promise)
|
||||
internals.openBrowser = open
|
||||
let disposing: Promise<void> | 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<void>((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<undefined>()
|
||||
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<undefined>()
|
||||
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<void>))
|
||||
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()
|
||||
})
|
||||
@@ -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<typeof import('node:child_process')>(),
|
||||
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, '<head></head><body>shell</body>')
|
||||
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<WebServer, 'host' | 'port' | 'protocol' | 'getOrigin' | 'registerFallback' | 'renderIndex'> = {
|
||||
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<void> = async () => {}): void {
|
||||
ctx.provide('loader', { await: settle, entries: () => [] } as never)
|
||||
return server as WebServer
|
||||
}
|
||||
|
||||
interface BashContribution {
|
||||
@@ -96,441 +49,143 @@ interface BashContribution {
|
||||
resolve: () => Record<string, string>
|
||||
}
|
||||
|
||||
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<void>((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<void>((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<void>))
|
||||
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<undefined>()
|
||||
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$/)
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
@@ -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).
|
||||
|
||||
-----
|
||||
|
||||
<a id="browser-authentication-and-request-trust"></a>
|
||||
## 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).
|
||||
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -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) 提供。
|
||||
|
||||
-----
|
||||
|
||||
<a id="browser-authentication-and-request-trust"></a>
|
||||
## 浏览器认证与请求信任
|
||||
|
||||
通过 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)。
|
||||
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -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:*",
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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<void> {
|
||||
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
|
||||
@@ -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<ConnectionConfig> = 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<void> {
|
||||
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)
|
||||
|
||||
@@ -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<RpcIdType>('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<PeerId, PeerRecord>()
|
||||
readonly authentication: ConnectionAuthentication
|
||||
private readonly owner: Context
|
||||
private disposed = false
|
||||
private readonly interceptors = new Map<string, ConnectionRpcInterceptor>()
|
||||
@@ -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<void> | 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(
|
||||
|
||||
@@ -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<Record<string, string | readonly string[] | undefined>>
|
||||
}
|
||||
|
||||
/** 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<Record<string, string>>): 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<void>
|
||||
}
|
||||
| { 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. */
|
||||
|
||||
@@ -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<void> | 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<void> | 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<void> | 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 })
|
||||
})
|
||||
@@ -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])
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<WebServer['renderIndex']>[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<string, string>, 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<string, string>, 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<URL> {
|
||||
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<string> {
|
||||
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<string, string> = {},
|
||||
): Promise<{ cookie: string; state: ReturnType<typeof fakeResponse>['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()
|
||||
|
||||
@@ -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<WebRoute['handler']>((_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<number | undefined>((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<Connection.ConnectionRpcHandler>(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<WebRoute['handler']>((_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()
|
||||
})
|
||||
@@ -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",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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',
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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')
|
||||
|
||||
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user