diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml
index b7f69935ec..bdfa46c623 100644
--- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml
@@ -9,14 +9,14 @@
en: 01293500639c9d79
zh: 6d19e4843955c811
/agent-note-browser-launch-token-authentication/decision:
- en: 0c437d201b8668d5
- zh: 2c1b3e67b38a5012
+ en: 42fd63aa09083a10
+ zh: f2536e571c5fe4e2
/agent-note-browser-launch-token-authentication/verification:
- en: 51fe0a5b45693654
- zh: 69c82207975fa421
+ en: 99022b3decf8b596
+ zh: 8ff360a934ccfe5c
/agent-note-browser-launch-token-authentication/alternatives-considered:
- en: 5275c87f19fe6eee
- zh: ccb922367c4bb3e2
+ en: 226046f2546fceb7
+ zh: 2c03d95e2c16c2f5
/agent-note-browser-launch-token-authentication/consequences:
- en: 5d69529b50c1ff32
- zh: 5fc371b5cde4783e
+ en: 530a40576d8b3f9f
+ zh: 59f2dd4809ccbe37
diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md
index 2a8d5e5319..abefbb9ee8 100644
--- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md
+++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md
@@ -18,6 +18,8 @@ The Token plugin generates one random launch token per Host root and retains it
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.
+Browsers scope cookies by hostname and not by port, so each signed-in port adds its cookie to every request for that hostname, and Node.js answers 431 before any handler runs once request headers pass 16,384 bytes. A successful root exchange therefore expires the other authorities' generated-name cookies its request carries, except the 16 with the latest claimed issue time. The issue time is read without signature verification because another Harness home signs with a different secret; the claim only orders cookies for expiry and never authenticates. `/connect` exchanges expire nothing.
+
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 +28,7 @@ The shipped CLI accepts concrete local bind addresses but rejects wildcard addre
## Verification
-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.
+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, cleanup of obsolete token URLs backed by valid cookies, and expiry of other authorities' cookies beyond the 16 most recently issued. The Token Loader test sends a sign-in carrying 17 other ports' cookies to a real listener and receives one expiry. 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
@@ -40,12 +42,16 @@ Unit coverage pins process-token retention across Token plugin reloads, one secr
**Add logout, TLS-proxy, and forwarding-header configuration.** None is required by the loopback Web application or the reported authentication gap. Adding them would define deployment contracts without current consumers. Browser site-data controls revoke one browser session; deleting the credential record and restarting the process revokes all sessions.
+**Bound cookie growth with one shared cookie name, a shorter lifetime, or a larger header limit.** One name lets a sign-in on one port replace another port's cookie, so two ports cannot stay signed in together. A shorter lifetime does not bound how many ports one day adds. A larger limit on this listener leaves the cookies in place for every other server on that hostname and for browsers that keep an unbounded number per host. Expiring the earliest other cookies at sign-in keeps names, lifetime, and concurrently signed-in ports.
+
## Consequences
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 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.
+One browser stays signed in to at most 17 authorities of one hostname: the latest sign-in and the 16 most recently issued others. A sign-in ranks the others by issue time, not by last use, so an authority in daily use loses its cookie once 17 other authorities have signed in after it, and needs its launch URL again.
+
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.
The [native HTTPS listener decision](2026-09-23-native-https-web-listener.md) supersedes the HTTP-only transport and omitted-`Secure` assumptions here. Listener protocol now determines `Secure`; the token exchange, signed-cookie authority, and credential lifetime remain owned by this note.
diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md
index 14ac57ae33..8d29c4008e 100644
--- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md
+++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md
@@ -18,6 +18,8 @@ Token 插件为每个 Host 根生成一个随机启动令牌,并跨插件重
cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。HTTP 监听器不设置 `Secure`。这里没有 logout 操作。
+浏览器按 hostname 而非 port 划分 cookie,因此每个已登录 port 都会把自己的 cookie 加到发往该 hostname 的每个请求中;请求头超过 16,384 字节后,Node.js 会在任何 handler 运行前返回 431。成功的根路径交换因此让请求携带的其他 authority 的生成格式 cookie 过期,只保留声明的签发时间最新的 16 个。签发时间在不验证签名的情况下读取,因为其他 Harness home 使用不同的密钥签名;该声明只用于排列过期顺序,绝不用于认证。`/connect` 交换不让任何 cookie 过期。
+
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 +28,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session`
## 验证
-单元覆盖 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。
+单元覆盖 Token 插件重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录、用有效 cookie 清理过时令牌 URL,以及让签发时间最新的 16 个之外的其他 authority cookie 过期。Token Loader 测试向真实 listener 发送携带 17 个其他 port cookie 的登录请求,并收到一条过期指令。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。
## 曾考虑的替代方案
@@ -40,12 +42,16 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session`
**增加 logout、TLS 代理和转发 header 配置。** loopback Web 应用与已报告认证缺口都不需要这些能力;加入它们会在没有当前 consumer 时定义部署约定。浏览器站点数据控制会撤销单个浏览器会话;删除凭据记录并重启进程会撤销全部会话。
+**用单一共享 cookie 名称、更短的有效期或更大的请求头上限来限制 cookie 增长。** 单一名称会让某个 port 的登录替换另一个 port 的 cookie,两个 port 无法同时保持登录。更短的有效期无法限制一天内新增的 port 数量。提高本 listener 的上限后,这些 cookie 仍会发给该 hostname 上的其他服务,在不限制每个 host cookie 数量的浏览器中也会继续增长。在登录时让最早的其他 cookie 过期,可以保留名称、有效期和同时登录的 port。
+
## 后果
持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。
持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Token 验证器在每个请求上使用已加载的密钥。如果 HTTP listener 的 authority 经未加密网络可达,cookie 就可能以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。
+同一浏览器在同一 hostname 下最多保持 17 个 authority 的登录:最近一次登录的 authority,以及签发时间最新的另外 16 个。登录时按签发时间而非最近使用排列其他 authority,因此每天都在使用的 authority,在另外 17 个 authority 于其后登录时会失去 cookie,需要重新打开其启动 URL。
+
本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。
[原生 HTTPS 监听器决策](2026-09-23-native-https-web-listener.zh.md)取代本说明仅支持 HTTP 传输及不设置 `Secure` 的前提。`Secure` 由监听器协议决定;令牌交换、签名 cookie 的 authority 与凭据有效期仍由本说明定义。
diff --git a/packages/host/authentication-token/README.i18n.yaml b/packages/host/authentication-token/README.i18n.yaml
index fabbeee921..4e59673ca0 100644
--- a/packages/host/authentication-token/README.i18n.yaml
+++ b/packages/host/authentication-token/README.i18n.yaml
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 6e85873f6f5f222a
/deepseek-ai-dsh-host-authentication-token/use-this-package:
- en: 3d20e5d3cb713786
- zh: 0bf29d01c2dddfaa
+ en: 380390d48b2a753d
+ zh: cd77322ae033f4e8
/deepseek-ai-dsh-host-authentication-token/understand-the-implementation:
en: 6a5250377ab73cd3
zh: b1c6a2f94f19efa0
@@ -30,8 +30,8 @@
en: bc510c5c25c0204f
zh: 55366b46ba23f1eb
/deepseek-ai-dsh-host-authentication-token/known-limitations-and-deferred-work:
- en: 7700f421f2c53016
- zh: 3d711811688b26de
+ en: 5a62f0fb6027d148
+ zh: f410098162e94f2e
/deepseek-ai-dsh-host-authentication-token/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 8ec3e73528ddb1a6
diff --git a/packages/host/authentication-token/README.md b/packages/host/authentication-token/README.md
index 080fe015b8..ca3612902d 100644
--- a/packages/host/authentication-token/README.md
+++ b/packages/host/authentication-token/README.md
@@ -35,6 +35,8 @@ Configure `printUrl` and `openBrowser` on the WebApp runtime, not this plugin. A
A root request carrying the launch-token query is handled by the original token exchange: successful `GET /` returns 303 with a Cookie and redirects to `./`; invalid credentials return 401. Requests on other paths continue to their route owner. When WebApp collects entries after readiness, this plugin appends its process token to the supplied base URL while preserving its authority, path, and other query fields. The contributed entry is eligible for automatic opening. Token neither reads WebApp services nor owns printing, readiness, or the native browser opener.
+Browsers send one hostname's Cookies to every port, so the Cookies of all signed-in authorities on that hostname travel in one `Cookie` request header. A successful root exchange therefore also expires the other authorities' Cookies its request carries, except the 16 with the latest claimed issue time. It selects only names of the generated form and reads the issue time without verifying the signature, because another Harness home signs with a different secret. `/connect` exchanges expire nothing.
+
Browser v1 Cookies authenticate to one shared Peer owned by this plugin. `/connect` declares anonymous route admission: Connection checks the source, then the handler verifies the launch token, creates an API Peer, and signs its ID in a v2 Cookie. A valid v2 Cookie authenticates pages and API requests through the same Provider. The Peer's principal and RemoteAccess determine permissions; there is no page/API purpose level. Token permits one `/api/remote.mux` Socket per API Peer: duplicate attachment returns 409 without revoking the first connection. Closing that Socket revokes the credential synchronously, then disposes the Peer; later requests using that Cookie are refused. Other upgrade routes, including Inspector CDP, neither claim the Peer nor revoke it on closure.
The signing secret remains the `client-connection/browser-session` grant record in Credentials. Cookie names, signed audiences, expiry validation, and the listener-controlled `Secure` attribute follow the existing protocol. Reloading retains this root application's launch token and still-valid Cookies while creating a new plugin-owned shared Peer. Token activation failure may leave the application running without this verifier; it does not permit unauthenticated access to protected routes. Desktop can mount this Provider alongside its private-credential Provider.
@@ -78,6 +80,8 @@ None; authentication does not modify model requests.
- Browser Cookies share one plugin-owned Peer; ending the plugin scope ends its live connections together.
+- One browser stays signed in to at most 17 authorities of one hostname: the latest sign-in and the 16 most recently issued others. The root exchange ranks by issue time, not by last use; an authority whose Cookie it expires answers 401 on the next page load until its launch URL is opened again.
+- A browser whose `Cookie` header already exceeds the 16,384-byte request-header limit of Node.js receives 431 before the exchange runs, so nothing expires until the user clears that hostname's site data. Sign-ins on Hosts that expire nothing still add Cookies.
- Plain HTTP transports bearer Cookies without encryption. Listener TLS determines the Cookie's `Secure` attribute.
- The token middleware owns only the root token exchange. Other HTML or product paths keep their route owner's handling, including any token query on those paths.
diff --git a/packages/host/authentication-token/README.zh.md b/packages/host/authentication-token/README.zh.md
index f0eb7e1691..e139d344d7 100644
--- a/packages/host/authentication-token/README.zh.md
+++ b/packages/host/authentication-token/README.zh.md
@@ -35,6 +35,8 @@ kind: "package-reference"
携带启动 Token query 的根路径请求由原 Token 交换处理:成功的 `GET /` 返回303、写入 Cookie,并重定向到 `./`;无效凭据返回401。其他路径的请求交给其路由 owner。WebApp 就绪后收集入口时,本插件向传入的基地址追加进程 Token,同时保留 authority、路径与其他 query 字段。贡献的入口允许自动打开。Token 不读取 WebApp 服务,也不拥有打印、就绪判断或原生浏览器打开器。
+浏览器会把同一 hostname 的 Cookie 发给每个 port,因此该 hostname 下所有已登录 authority 的 Cookie 会出现在同一个 `Cookie` 请求头中。成功的根路径交换因此还会让请求携带的其他 authority 的 Cookie 过期,只保留声明的签发时间最新的 16 个。它只选取符合生成格式的名称,并在不验证签名的情况下读取签发时间,因为其他 Harness home 使用不同的密钥签名。`/connect` 交换不让任何 Cookie 过期。
+
浏览器 v1 Cookie 认证为本插件拥有的共享 Peer。`/connect` 声明匿名路由准入:Connection 检查来源,handler 随后验证启动 Token、创建 API Peer,并在 v2 Cookie 中签入其 ID。有效 v2 Cookie 通过同一 Provider 认证页面与 API 请求。Peer 的 principal 与 RemoteAccess 决定权限,不区分页面/API purpose 等级。Token 限制每个 API Peer 只有一条 `/api/remote.mux` Socket;重复关联返回409,不撤销首条连接。该 Socket 关闭时先同步撤销凭据,再释放 Peer;后续使用该 Cookie 的请求被拒绝。其他升级路由(包括 Inspector CDP)不认领该 Peer,也不在关闭时撤销它。
签名密钥仍使用 Credentials 的 `client-connection/browser-session` grant 记录。Cookie 名称、签名 audience、有效期验证及监听器决定的 `Secure` 属性遵循既有协议。重载保留根应用的启动 Token 与尚有效 Cookie,同时创建新的插件共享 Peer。Token 激活失败允许应用在缺少此验证器时继续运行,但不允许未认证访问受保护路由。Desktop 可以同时挂载本 Provider 与私有凭据 Provider。
@@ -78,6 +80,8 @@ kind: "package-reference"
- 浏览器 Cookie 共用一个插件 Peer;结束插件作用域时,其存活连接一同结束。
+- 同一浏览器在同一 hostname 下最多保持 17 个 authority 的登录:最近一次登录的 authority,以及签发时间最新的另外 16 个。根路径交换按签发时间而非最近使用排序;Cookie 被过期的 authority 在下次加载页面时返回 401,直到重新打开其启动 URL。
+- 浏览器的 `Cookie` 请求头若已超过 Node.js 的 16,384 字节请求头上限,会在交换运行前收到 431,因此在用户清除该 hostname 的站点数据之前不会有任何 Cookie 过期。在不执行过期的 Host 上登录仍会增加 Cookie。
- 明文 HTTP 不加密 bearer Cookie。Cookie 的 `Secure` 属性由监听器 TLS 决定。
- Token 中间件只拥有根路径交换。其他 HTML 或产品路径仍由路由 owner 处理,包括这些路径上的 token query。
diff --git a/packages/host/authentication-token/src/browser-auth.ts b/packages/host/authentication-token/src/browser-auth.ts
index 77813fda48..4182e07ff7 100644
--- a/packages/host/authentication-token/src/browser-auth.ts
+++ b/packages/host/authentication-token/src/browser-auth.ts
@@ -17,6 +17,17 @@ const DAY_MILLISECONDS = 24 * 60 * 60 * 1000
const SECRET_BYTES = 32
const TOKEN_QUERY = 'token'
const COOKIE_PREFIX = 'dsh-auth-'
+/** Exactly the names `cookieName` generates: the prefix and an unpadded base64url SHA-256 digest. */
+const GENERATED_COOKIE_NAME = new RegExp(`^${COOKIE_PREFIX}[A-Za-z0-9_-]{43}$`, 'u')
+/**
+ * Other authorities' cookies a browser sign-in leaves in place. Browsers send one hostname's
+ * cookies to every port, so each signed-in port adds a 226-character pair to every request, and
+ * Node.js 24 answers 431 before any handler runs once request headers pass 16,384 bytes: measured
+ * with Chromium 149, at about 70 cookies. Sixteen others keep the `Cookie` header near 3.9 KB and
+ * leave room for about 50 sign-ins on Hosts that expire nothing. Raise it only while that room
+ * remains and Node.js keeps this default limit.
+ */
+const RETAINED_OTHER_COOKIES = 16
const COOKIE_PAYLOAD_VERSION = 1
const STORED_SECRET_VERSION = 1
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]*$/
@@ -118,17 +129,60 @@ function cookieName(authority: string): string {
return COOKIE_PREFIX + encodeBase64Url(createHash('sha256').update(authority).digest())
}
-/** Read the exact generated cookie without implementing general Cookie decoding. */
-function cookieValue(headerValue: string, name: string): string | undefined {
+/** Split a Cookie header into name and value pairs without implementing general Cookie decoding. */
+function cookiePairs(headerValue: string): [name: string, value: string][] {
+ const pairs: [string, string][] = []
for (const segment of headerValue.split(';')) {
const at = segment.indexOf('=')
- if (at === -1 || segment.slice(0, at).trim() !== name) continue
- return segment.slice(at + 1).trim()
+ if (at !== -1) pairs.push([segment.slice(0, at).trim(), segment.slice(at + 1).trim()])
}
- return undefined
+ return pairs
}
-/** Serialize the fixed browser-session attributes; generated names and values are cookie-safe base64url. */
+/** Read the exact generated cookie; the first pair of that name wins. */
+function cookieValue(headerValue: string, name: string): string | undefined {
+ return cookiePairs(headerValue).find(([candidate]) => candidate === name)?.[1]
+}
+
+/**
+ * Issue time a cookie value claims, read without checking its signature: another Harness home
+ * signs with a secret this process does not hold. The result only orders cookies for expiry and
+ * never authenticates. An unreadable value counts as issued at time zero.
+ */
+function claimedIssuedAt(value: string): number {
+ const body = decodeBase64Url(value.split('.')[1] ?? '')
+ if (body === undefined) return 0
+ try {
+ const decoded: unknown = JSON.parse(body.toString('utf8'))
+ return isRecord(decoded) && typeof decoded.issuedAt === 'number' && Number.isSafeInteger(decoded.issuedAt)
+ ? decoded.issuedAt
+ : 0
+ } catch {
+ return 0
+ }
+}
+
+/**
+ * Select the other authorities' cookies a sign-in expires: every generated-name cookie in the
+ * request except `ownName` and the `RETAINED_OTHER_COOKIES` with the latest claimed issue time.
+ * Equal times keep request order.
+ */
+function supersededCookieNames(headerValue: string | undefined, ownName: string): string[] {
+ if (headerValue === undefined) return []
+ const issued = new Map()
+ for (const [name, value] of cookiePairs(headerValue)) {
+ if (name !== ownName && GENERATED_COOKIE_NAME.test(name)) issued.set(name, claimedIssuedAt(value))
+ }
+ return [...issued]
+ .sort(([, left], [, right]) => right - left)
+ .slice(RETAINED_OTHER_COOKIES)
+ .map(([name]) => name)
+}
+
+/**
+ * Serialize the fixed browser-session attributes; generated names and values are cookie-safe
+ * base64url. An empty value with a zero lifetime makes the browser delete the cookie of that name.
+ */
function sessionCookie(
name: string,
value: string,
@@ -252,7 +306,10 @@ export class BrowserAuth {
* Authenticate an index request. A valid root query token mints the cookie
* and redirects to the directory-relative clean `./`; a valid cookie lets
* the caller serve the index; every other request receives the same minimal
- * 401 response.
+ * 401 response. The minting response also expires the other authorities'
+ * generated-name cookies its request carries, except the
+ * `RETAINED_OTHER_COOKIES` with the latest claimed issue time, so one
+ * browser's `Cookie` header stays bounded.
* @param req - incoming root or configured-index request.
* @param res - response owned when this method returns false.
* @param secure - whether the listener receiving this request serves TLS; the
@@ -277,13 +334,16 @@ export class BrowserAuth {
issuedAt,
expiresAt,
}, this.secret)
+ const name = cookieName(authority)
+ const minted = sessionCookie(name, value, expiresAt, Math.floor(this.maxAgeMilliseconds / 1000), secure)
+ const superseded = supersededCookieNames(header(req.headers, 'cookie'), name)
+ .map(other => sessionCookie(other, '', 0, 0, secure))
res.writeHead(303, {
'cache-control': 'no-store',
'location': './',
'referrer-policy': 'no-referrer',
- 'set-cookie': sessionCookie(
- cookieName(authority), value, expiresAt, Math.floor(this.maxAgeMilliseconds / 1000), secure,
- ),
+ // A lone cookie stays one string for callers that read a single Set-Cookie value.
+ 'set-cookie': superseded.length === 0 ? minted : [minted, ...superseded],
})
res.end()
return false
diff --git a/packages/host/authentication-token/src/types.ts b/packages/host/authentication-token/src/types.ts
index 72b8854dcb..f7d254a06d 100644
--- a/packages/host/authentication-token/src/types.ts
+++ b/packages/host/authentication-token/src/types.ts
@@ -7,9 +7,9 @@ export interface ConnectionIndexRequest extends ConnectionTrustRequest {
readonly url?: string | undefined
}
-/** Response operations used by the token implementation. */
+/** Response operations used by the token implementation; an array header value writes one header line per element. */
export interface ConnectionIndexResponse {
- writeHead(status: number, headers?: Readonly>): unknown
+ writeHead(status: number, headers?: Readonly>): unknown
end(body?: string): unknown
}
diff --git a/packages/host/authentication-token/tests/browser-auth.host.spec.ts b/packages/host/authentication-token/tests/browser-auth.host.spec.ts
index 010ef1b46f..f1c4de82ea 100644
--- a/packages/host/authentication-token/tests/browser-auth.host.spec.ts
+++ b/packages/host/authentication-token/tests/browser-auth.host.spec.ts
@@ -28,10 +28,14 @@ function signedBodyCookie(store: RecordCredentials, name: string, body: string):
interface ResponseState {
status?: number
- headers?: Readonly>
+ headers?: Readonly>
body?: string
}
+function setCookies(state: ResponseState): string[] {
+ return [state.headers?.['set-cookie'] ?? []].flat()
+}
+
function response(): { value: ConnectionIndexResponse; state: ResponseState } {
const state: ResponseState = {}
return {
@@ -78,16 +82,34 @@ function exchange(
auth: BrowserAuth,
authority = '127.0.0.1:3080',
secure = false,
+ cookie?: string,
): { cookie: string; launchUrl: string; state: ResponseState } {
const launchUrl = auth.authenticatedUrl(`http://${authority}`)
const target = new URL(launchUrl)
const res = response()
- expect(auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority), res.value, secure)).toBe(false)
- const setCookie = res.state.headers?.['set-cookie']
+ const init = cookie === undefined ? {} : { cookie }
+ expect(auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority, init), res.value, secure)).toBe(false)
+ const setCookie = setCookies(res.state)[0]
if (setCookie === undefined) throw new Error('token exchange did not set a cookie')
return { cookie: setCookie.split(';', 1)[0]!, launchUrl, state: res.state }
}
+/** One sign-in per port, issued one second apart from `startPort` upward. */
+function signedInPorts(auth: BrowserAuth, startPort: number, count: number): string[] {
+ return Array.from({ length: count }, (_, index) => {
+ vi.advanceTimersByTime(1000)
+ return exchange(auth, `127.0.0.1:${String(startPort + index)}`).cookie
+ })
+}
+
+function cookieNameOf(pair: string): string {
+ return pair.slice(0, pair.indexOf('='))
+}
+
+function expired(pair: string, secure = false): string {
+ return `${cookieNameOf(pair)}=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict${secure ? '; Secure' : ''}`
+}
+
afterEach(() => {
vi.useRealTimers()
})
@@ -124,7 +146,7 @@ describe('API credentials', () => {
return res.value.writeHead(status, headers)
},
}, false, publish)
- const cookie = res.state.headers?.['set-cookie']?.split(';', 1)[0]
+ const cookie = setCookies(res.state)[0]?.split(';', 1)[0]
if (cookie === undefined) throw new Error('API connect did not set a cookie')
const [name, value] = cookie.split('=') as [string, string]
const payload = { version: 2, authority, id, issuedAt, expiresAt: issuedAt + 30 * 86_400_000 }
@@ -253,7 +275,7 @@ describe('BrowserAuth', () => {
const token = mounted.searchParams.get('token')
const exchanged = response()
expect(auth.authorizeIndex(request(`/?token=${String(token)}`, 'gateway.example'), exchanged.value)).toBe(false)
- const setCookie = exchanged.state.headers?.['set-cookie']
+ const setCookie = setCookies(exchanged.state)[0]
if (setCookie === undefined) throw new Error('mount exchange did not set a cookie')
expect(auth.isAuthenticated(request(
'/', 'gateway.example', { cookie: setCookie.split(';', 1)[0]! },
@@ -327,6 +349,56 @@ describe('BrowserAuth', () => {
expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false)
})
+ it('expires all but the 16 most recently issued cookies of other ports when it signs in', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-11-20T00:00:00.000Z'))
+ const auth = await createAuth(new RecordCredentials())
+ const previous = exchange(auth).cookie
+ const others = signedInPorts(auth, 40_000, 19)
+ vi.advanceTimersByTime(1000)
+
+ const within = exchange(auth, '127.0.0.1:3080', false, [previous, ...others.slice(3)].join('; '))
+ expect(within.state.headers?.['set-cookie']).toBeTypeOf('string')
+
+ // Request order is unrelated to issue order; the three earliest sign-ins go.
+ const crowded = exchange(auth, '127.0.0.1:3080', false, [
+ 'theme=dark', ...[...others].reverse(), previous, 'dsh-auth-fixture=signed', 'flag',
+ ].join('; '))
+ expect(setCookies(crowded.state)).toEqual([
+ expect.stringMatching(new RegExp(`^${cookieNameOf(previous)}=v1\\..*; Max-Age=2592000; Path=/; `, 'u')),
+ expired(others[2]!), expired(others[1]!), expired(others[0]!),
+ ])
+ expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: crowded.cookie }))).toBe(true)
+
+ const tls = exchange(auth, '127.0.0.1:3080', true, others.slice(0, 17).join('; '))
+ expect(setCookies(tls.state).slice(1)).toEqual([expired(others[0]!, true)])
+ })
+
+ it('orders other ports by the issue time their cookies claim, unreadable values first', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-11-20T00:00:00.000Z'))
+ // Another Harness home signs with a secret this process cannot verify.
+ const elsewhere = signedInPorts(await createAuth(new RecordCredentials()), 41_000, 16)
+ const auth = await createAuth(new RecordCredentials())
+ const claim = (payload: unknown): string => `v1.${Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')}.unverified`
+ const unreadable = [
+ 'broken',
+ 'v1.%.unverified',
+ `v1.${Buffer.from('not json', 'utf8').toString('base64url')}.unverified`,
+ claim(null),
+ claim({ issuedAt: 'now' }),
+ claim({ issuedAt: Date.now() + 0.5 }),
+ ].map((value, index) => `${cookieNameOf(exchange(auth, `127.0.0.1:${String(42_000 + index)}`).cookie)}=${value}`)
+ const repeated = `${cookieNameOf(elsewhere[0]!)}=${claim({ issuedAt: Date.now() + 60_000 })}`
+
+ const signedIn = exchange(auth, '127.0.0.1:3080', false, [...unreadable, ...elsewhere].join('; '))
+ expect(setCookies(signedIn.state).slice(1)).toEqual(unreadable.map(pair => expired(pair)))
+
+ // A name that appears twice counts once.
+ const repeatedName = exchange(auth, '127.0.0.1:3080', false, [unreadable[0]!, ...elsewhere, repeated].join('; '))
+ expect(setCookies(repeatedName.state).slice(1)).toEqual([expired(unreadable[0]!)])
+ })
+
it('loads one secret per activation and replaces it after deletion on the next activation', async () => {
const store = new RecordCredentials()
const auth = await createAuth(store)
diff --git a/packages/host/authentication-token/tests/loader.host.spec.ts b/packages/host/authentication-token/tests/loader.host.spec.ts
index e4b45e1de3..ba7ee33812 100644
--- a/packages/host/authentication-token/tests/loader.host.spec.ts
+++ b/packages/host/authentication-token/tests/loader.host.spec.ts
@@ -1,4 +1,5 @@
/** Real Loader composition exercises Token as an independent authentication plugin. */
+import { createHash } from 'node:crypto'
import { request as httpRequest } from 'node:http'
import { once } from 'node:events'
import type { Duplex } from 'node:stream'
@@ -16,7 +17,8 @@ import { expect, it, onTestFinished } from 'vitest'
import * as Token from '../src/index.ts'
import { BrowserAuth } from '../src/browser-auth.ts'
-it('serves token exchanges through WebServer and keeps token-owned Peers outside Connection defaults', async () => {
+/** Loader-composed credentials, WebServer, Connection, and Token on an OS-assigned port. */
+async function composed(): Promise<{ ctx: Context; origin: string; auth: BrowserAuth }> {
const root = await mkdtemp(join(tmpdir(), 'dsh-token-plugin-'))
const ctx = new Context()
onTestFinished(async () => {
@@ -41,7 +43,11 @@ it('serves token exchanges through WebServer and keeps token-owned Peers outside
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(path).href } })
await ctx.loader.await()
const origin = `http://127.0.0.1:${ctx.webServer.port}`
- const auth = await BrowserAuth.create(ctx[Context.root], ctx.credentials, 30)
+ return { ctx, origin, auth: await BrowserAuth.create(ctx[Context.root], ctx.credentials, 30) }
+}
+
+it('serves token exchanges through WebServer and keeps token-owned Peers outside Connection defaults', async () => {
+ const { ctx, origin, auth } = await composed()
const login = new URL(auth.authenticatedUrl(origin))
expect(login.searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/)
const exchanged = await fetch(login, { redirect: 'manual' })
@@ -117,3 +123,23 @@ it('serves token exchanges through WebServer and keeps token-owned Peers outside
if ('rejection' in resumed) throw new Error('existing Cookie did not survive provider reload')
expect(resumed.peer).not.toBe(admission.peer)
})
+
+it('answers a sign-in that carries 17 other ports\' Cookies by expiring the earliest one', async () => {
+ const { ctx, origin, auth } = await composed()
+ const others = Array.from({ length: 17 }, (_, index) => {
+ const name = `dsh-auth-${createHash('sha256').update(`127.0.0.1:${String(40_000 + index)}`).digest('base64url')}`
+ const claim = Buffer.from(JSON.stringify({ issuedAt: 1_795_000_000_000 + index }), 'utf8').toString('base64url')
+ return { name, pair: `${name}=v1.${claim}.unverified` }
+ })
+ const exchanged = await fetch(auth.authenticatedUrl(origin), {
+ redirect: 'manual',
+ headers: { cookie: others.map(other => other.pair).join('; ') },
+ })
+ expect(exchanged.status).toBe(303)
+ const [minted, ...expired] = exchanged.headers.getSetCookie()
+ expect(expired).toEqual([
+ `${others[0]!.name}=; Max-Age=0; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict`,
+ ])
+ const headers = { host: new URL(origin).host, cookie: minted?.split(';', 1)[0] }
+ if ('rejection' in ctx.connection.authentication.authenticate({ headers })) throw new Error('minted Cookie was rejected')
+})