dsh-connect-workbuddy 5.24.6 → 5.24.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,114 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.24.8 (2026-11-16)
4
+
5
+ > 版本号是 **patch**:这是一次**文档 / 打包**修复版,默认行为零变化(开关仍默认关闭、无接口变化、
6
+ > 无破坏性改动),修的是「设置界面把用户导向一个装不出来的文件」这条已随 5.24.7 上线的死链。
7
+
8
+ ### 修复:`stableConversationId` 的设置说明不再指向包外文件
9
+
10
+ 5.24.7 的设置界面里,`stableConversationId` 那条开关的说明文案写着「详见
11
+ `docs/STABLE-KEY-SEMANTICS.md`」,但该文件**不在 `package.json` 的 `files` 白名单**——用户装出来的
12
+ 包里 `docs/` 只有 `PRIVACY.md`、`WINDOWS.md`、`assets`。跟着文案去翻,必然扑空:而这是这个实验开关
13
+ 在用户侧**唯一的说明入口**(README 不含它,设置文案是 GUI 里唯一渲染出来的引用)。
14
+
15
+ - **修法**:把 `docs/STABLE-KEY-SEMANTICS.md` 加入 `files` 白名单,让它真的随包发布,文案由此落地。
16
+ 这是全项目**唯一一处**会渲染进设置界面、且指向未随包文件的 `docs/` 指针(其余 `docs/*.md` 引用都在
17
+ `lib/*.js` 的 JSDoc 注释里,是开发者面包屑,不面向用户)——已由 `tests/privacy-gate.spec.ts` 新增
18
+ 的守护钉死:该守护**动态读取** schema 文案里的 `docs/*.md` 指针并要求它在白名单内,将来任何一方
19
+ 漂移(有人删条目、或换指向别的包外文件)都会变红,死链不会以同样的方式再次烂掉。
20
+ - **不改行为**:开关语义、默认值(`false`)、派生逻辑一律未动。
21
+
22
+ ### 归类更正:`stableConversationId` 的代码其实已随 5.24.7 进入 npm,此前 CHANGELOG 标为「未发布」名不副实
23
+
24
+ 本文件此前把 `stableConversationId` 挂在「## 未发布(实验性开关,默认关闭)」一节。事实是:该开关的
25
+ 代码随 5.24.7 一起进入了 npm 包(`lib/index.js` 含其 schema 与 wiring)。也就是说,**已发布 5.24.7
26
+ 的那份 CHANGELOG 自相矛盾**——它声称某物「未发布」,而这个包自己就带着它。下方一节已据实重标;开关
27
+ 本身仍是默认关闭的实验能力,本次不推广默认值、不附带命中率结论、不区分上游内部机制(限定见该节)。
28
+
29
+ ## 5.24.7 (2026-11-15)
30
+
31
+ > 版本号是 **patch**:默认行为零变化,修一处只在反代部署下触发的全量 403,并新增一个默认
32
+ > 关闭的可选配置项;无接口变化、无破坏性改动。来自 issue #261。
33
+
34
+ ### 新增:`trustedHosts`——反代部署下卡片路由不再全量 403(issue #261)
35
+
36
+ 把 DSH 装在 Docker / 服务器、前面挂反向代理时,插件设置卡片会整块空白、所有
37
+ `/plugins/dsh-connect-workbuddy/*` 返回 `403 {"error":"host-not-trusted"}`,而 DSH 自己的
38
+ 页面与 `/api` 正常。原因是卡片路由的 Host/Origin 闸门拿 `req.socket.localAddress` 与 `Host`
39
+ 比较,而反代后面宿主绑定回环、这个值恒为 `127.0.0.1`,浏览器发来的对外 authority 永远对不上;
40
+ 宿主自己的栅栏用 `dsh web --trusted-host` 声明的 authority 放行同一个 Host,于是两边分叉。
41
+
42
+ - **新增默认空的 `trustedHosts` 配置**(volatile、请求时读取,改动无需重载)。元素是裸
43
+ `host[:port]`:不带端口匹配该主机名任意端口,带端口精确匹配该 authority;加载期逐条校验,
44
+ 写错直接报错而不是悄悄授权一个前缀。Host 与 Origin 两道闸门共用同一份列表与同一套
45
+ WHATWG 归一化(大小写、IPv6 括号、scheme 默认端口)。
46
+ - **默认行为零变化**:空列表时回环、LAN 绑定、`0.0.0.0`/`[::]` 显式拒绝、DNS rebinding 防护
47
+ 全部与之前一致。白名单只把「本机地址」的定义从「socket 落在哪」扩展到「部署方声明的权威」,
48
+ 与宿主 `--trusted-host` 对齐;Host/Origin 本就可伪造、不是鉴权,威胁模型不变。
49
+ - **不读宿主的 `connection.trustedHosts`**:该字段在 `HostConnectionService` 上是 private,
50
+ 且依赖另一个服务在场会让 `connection` 缺席时卡片整块消失。白名单放在本插件自己的 Config,
51
+ 自包含、与宿主版本无关(详见 `docs/ISSUE-261-REPLY.md`)。
52
+ - **卡片不再把 403 吞成空白**:`refreshUsage` 现在读响应体里的 `error`,对
53
+ `host-not-trusted` / `origin-not-trusted` 给一条专属、可操作的提示(改本机地址打开,或配
54
+ `trustedHosts`),并抑制「重新登录 WorkBuddy」「服务可能刚重启」这两条对此**事实错误**的建议;
55
+ 其它 403 / 500 / 未登录仍走原路径。带一个「重试」按钮,修好后可立即重读。
56
+
57
+ 验证:`tests/loopback.spec.ts`(信任判定 + authority 校验)、`tests/web-status.spec.ts`(反代
58
+ 场景 403→200、未命中仍 403、Origin 半边、端口语义、空列表等价)、`tests/issue261-gate-hint.spec.tsx`
59
+ (门禁码专属文案、其它错误零影响、恢复后清除)。三层各做一次变异验证:禁用信任匹配 / 放宽门禁码
60
+ 判定 / 移除 Origin 半边信任,对应测试均转红。
61
+
62
+ ## 实验性开关 `stableConversationId`(默认关闭;代码随 5.24.7 进入 npm,本节此前误标「未发布」)
63
+
64
+ ### 新增:可选 `stableConversationId`(opt-in,默认 `false`)
65
+
66
+ 新增一个**默认关闭**的实验性配置开关 `stableConversationId`,用于让使用者在受控条件下对照
67
+ 「稳定 `X-Conversation-ID` 与隐式前缀缓存命中之间的关系」。语义与已知限制的权威定义见
68
+ [`docs/STABLE-KEY-SEMANTICS.md`](docs/STABLE-KEY-SEMANTICS.md)(路线 A:请求前缀派生的亲和键实验)。
69
+
70
+ - **默认行为零变化**:`stableConversationId` 默认 `false`,默认路径中 `X-Conversation-ID` 等三件套
71
+ 仍然每请求现生成、互不相同。
72
+ - **开启后只影响 `X-Conversation-ID`**:由 `deriveStableConversationId(bodyJson)` 从
73
+ `model` + 首条 `system` + 第一条真实 `user` 经规范化后派生一个 v4 形状的稳定值;
74
+ `X-Conversation-Request-ID` / `X-Conversation-Message-ID` / `X-Root-Request-ID` 仍每请求现生成。
75
+ - **配置在插件挂载时采样一次**,改动后需重载插件才生效。
76
+ - 派生键派生自请求内容,**不是宿主 `sessionId`**:压缩 / 首问变化 / 模型切换 / 会话分叉都可能换键,
77
+ 前缀相同的独立会话会共享键;解析失败或缺字段时显式回退到每请求现生成。
78
+
79
+ > 本开关是实验性、默认关闭的可选能力。**不附带任何命中率实测结论、不声称稳定 ID 能改善命中、
80
+ > 不区分上游缓存键分区与路由亲和等内部机制,也不推广默认值。** 真实上游实验、完整链路验证与 GA
81
+ > 决策属于后续单独工作,须由使用者在指定构建/账号/模型/时间窗口下自行验证并采用限定措辞。
82
+
83
+ 验证:新增 `tests/upstream.spec.ts` 的离线 wire 级单测(默认关闭字节一致、派生键稳定性与回退、
84
+ 注入块跳过、多模态首问、NUL 歧义、无状态泄漏等)。
85
+
86
+ ### 新增:`stableConversationId` 的真实上游单变量对照证据与复现工具
87
+
88
+ 新增一组**纯 `scripts/` + `tests/` + `docs/` 的可离线复算证据**,把「稳定 `X-Conversation-ID`
89
+ 与隐式前缀缓存命中之间的关系」交给维护者与第三方独立复核;**不改 `src/`、不改默认值、不改开关行为**。
90
+ 权威说明与全部限定见 [`docs/E-PHASE-EVIDENCE.md`](docs/E-PHASE-EVIDENCE.md)。
91
+
92
+ - **证据**:`evidence/batch-1`、`evidence/batch-2` 两批脱敏 JSONL + `SHA256SUMS.txt`,可
93
+ `shasum -a 256 -c` 核验字节;`node scripts/recompute-probe-real.mjs --in <jsonl>` 纯离线复算。
94
+ - **如实各报各的,不合并不择优**:第一批 `DATA INCOMPLETE` / `NOT_EVALUATED`(19/20 组完整,
95
+ 一次孤立网络错误,未补跑未删不利数据);第二批全新独立重跑 `DATA COMPLETE` /
96
+ `BENEFIT_SUPPORTED`(20/20,配对平均差 91.4 个百分点、95% 区间 `[87.3, 95.4]`)。
97
+ - **工具**:`scripts/probe-core.ts`(零 I/O 纯函数)、`probe-stable-conversation-id-real.mjs`
98
+ (真实上游驱动,`--real --e-phase-authorized` 双 flag 门控、默认 `NOT_RUN`;门控先于加载
99
+ `lib/`,未授权路径无需构建即可运行)、`probe-usage-adapter.ts`(usage 双字段适配)、
100
+ `recompute-probe*.mjs`(离线复算)与三份离线单测(含 `tests/probe-real-gate.spec.ts`:
101
+ 门控与账号选择的守护)。真实复现前仍须 `pnpm run build`(与 PR #249 的探针一致);
102
+ `--real` 必须用 `--account-id` 显式指定 vault 账号,多账号未指定即拒绝。
103
+ - 证据文件、`probe-core.ts` 与 `probe-usage-adapter.ts` 保留原字节以对齐 `scriptHash`;驱动
104
+ 按评审修正后 `scriptHash` 变为新值,新旧哈希的对应关系与复算口径见
105
+ [`docs/E-PHASE-EVIDENCE.md`](docs/E-PHASE-EVIDENCE.md) §8。源码注释里遗留的历史内部指针由权威文档统一澄清。
106
+
107
+ > 这些读数仍是 **报告者实测、本插件/维护者尚未独立复现**(`docs/WINDOWS.md` §2 的 C 档):
108
+ > `MECHANISM_PROVEN false`,**不构成机制证明**、不区分缓存键分区与路由亲和、不外推其它账号/模型/端点,
109
+ > 也不把 C 档结论自动升级为可改默认值的 A/B 档。端到端完整链路验证(安装/重载/DSH→bili→插件→网关)
110
+ > **未完成**,不在结论内。开关仍默认 `false`,本 PR 不请求改默认值、不请求发版。
111
+
3
112
  ## 5.24.6 (2026-11-15)
4
113
 
5
114
  > 版本号是 **patch**:修一处「工具声明被悄悄放宽」的语义丢失,无新增配置项、无接口变化。
package/README.en.md CHANGED
@@ -657,6 +657,28 @@ node scripts/check-pii.mjs # non-zero exit blocks the release
657
657
 
658
658
  **Automated scanning only recognises the shapes it knows.** The first time you screenshot developer tools or paste a real device log, the rules will not cover it — look at it yourself, and add the new pattern to the rule table.
659
659
 
660
+ ## Reverse proxy / LAN access (issue #261)
661
+
662
+ When DSH runs in Docker / on a server behind Caddy, nginx or another reverse proxy, the plugin's settings card can be blank and every `/plugins/dsh-connect-workbuddy/*` route can answer `403 {"error":"host-not-trusted"}` — **while DSH's own pages and settings work**. This is not a sign-in problem; signing back into WorkBuddy cannot change it.
663
+
664
+ The card routes gate on Host/Origin: `Host` must equal the address the connection actually landed on (`req.socket.localAddress`). Behind a proxy the harness binds a loopback address, so that value is always `127.0.0.1`, while the proxy forwards the browser's `Host: <public authority>` unchanged — the two can never match. DSH's own `/api` uses a different fence that accepts the same Host via `dsh web --trusted-host <authority>`, which is why "the page works, the plugin is broken".
665
+
666
+ Fix: declare that public authority in the plugin's `trustedHosts` config (the same authority you pass to the host's `--trusted-host`):
667
+
668
+ ```yaml
669
+ # profile cordis.patch.yml, or the plugin's settings field
670
+ trustedHosts:
671
+ - 192.168.1.250:8443 # with port: matches exactly this authority
672
+ # - dsh.example.com # without port: matches that host on any port
673
+ ```
674
+
675
+ - **Empty by default** — loopback and direct LAN-bound deployments are unaffected.
676
+ - Each entry must be a bare `host[:port]` with no path, scheme or userinfo; a malformed value fails plugin load rather than silently granting a hostname prefix.
677
+ - It is a **volatile** field: changes take effect without a plugin reload / restart. Both the Host and Origin gates read the same list, so they cannot disagree.
678
+ - This is **not authentication**: Host/Origin are forgeable. The list only extends "this machine" from "where the socket landed" to "authority the deployer declared", matching the host's own fence. DNS-rebinding defense is unchanged (an attacker's domain is not on the list) and `0.0.0.0` / `[::]` are still refused.
679
+
680
+ If you would rather not configure it, simply **open DSH at its local address (`127.0.0.1`)** instead of the public / proxied address. Until it is fixed, the card now shows an explicit 403 hint instead of telling you to sign in again.
681
+
660
682
  ## Known limitations
661
683
 
662
684
  - The plugin depends on WorkBuddy client endpoints (not an official public API), so a WorkBuddy update may require adjustments.
package/README.md CHANGED
@@ -747,6 +747,28 @@ node scripts/check-pii.mjs # 退出码非 0 就不许发布
747
747
 
748
748
  **自动扫描只认它认识的那些形状。** 第一次截图开发者工具、第一次贴真机日志时,规则是盖不住的——那种时候必须人工再看一遍,并把新规律补进规则表。
749
749
 
750
+ ## 反向代理 / 局域网访问(issue #261)
751
+
752
+ 把 DSH 装在 Docker / 服务器上、前面再挂一层 Caddy、nginx 之类的反向代理时,插件的设置卡片可能整块空白、`/plugins/dsh-connect-workbuddy/*` 全部返回 `403 {"error":"host-not-trusted"}`——**而 DSH 自己的页面和设置是好的**。这不是登录问题,重新登录 WorkBuddy 改不了它。
753
+
754
+ 原因是卡片路由的 Host/Origin 闸门:它要求请求的 `Host` 等于连接实际落到的本机地址(`req.socket.localAddress`)。反代后面 DSH 绑定的是回环地址,这个值永远是 `127.0.0.1`;而代理默认**原样转发**浏览器发来的 `Host: <对外地址>`,两者永远不相等,于是闸门全部拒绝。DSH 自己的 `/api` 另有一套栅栏,用 `dsh web --trusted-host <地址>` 声明的 authority 放行同一个 Host,所以「页面能用、插件坏了」。
755
+
756
+ 修法:在插件配置里加一个 `trustedHosts`,把对外地址(与宿主的 `--trusted-host` 同一个 authority)声明进去:
757
+
758
+ ```yaml
759
+ # profile 的 cordis.patch.yml,或插件设置里对应字段
760
+ trustedHosts:
761
+ - 192.168.1.250:8443 # 带端口:只放行这一个 authority
762
+ # - dsh.example.com # 不带端口:该主机名任意端口都放行
763
+ ```
764
+
765
+ - **默认空**,本地回环 / 直接绑 LAN 地址的部署行为完全不变。
766
+ - 元素必须是裸 `host[:port]`,不能带路径、协议、用户名;写错会在插件加载时报错,而不是悄悄放行一个前缀。
767
+ - 它是 **volatile** 字段:加完立即生效,不需要重载插件或重启 DSH。Host 与 Origin 两道闸门读的是同一份列表,不会出现「Host 放行、Origin 又拦」。
768
+ - 这**不是鉴权**:Host/Origin 本就可伪造,白名单只是把「本机地址」的定义从「socket 落在哪」扩展到「部署方声明的权威」,与 DSH 主程序对齐。DNS rebinding 防护不变——攻击者页面的域名不在列表里,照样被拒;`0.0.0.0` / `[::]` 仍显式拒绝。
769
+
770
+ 如果不想配它,最简单的办法是**用 DSH 的本机地址(`127.0.0.1`)打开页面**,而不是对外地址或反代地址。修好后卡片会直接显示账号与积分;在修好之前,卡片会给出一条明确的 403 提示,不再让你去「重新登录」。
771
+
750
772
  ## 已知限制
751
773
 
752
774
  - 依赖 WorkBuddy 客户端接口(非官方开放 API),WorkBuddy 更新后插件可能需要随之调整。
@@ -0,0 +1,65 @@
1
+ # 稳定 `X-Conversation-ID` 的语义:路线 A(请求前缀派生的亲和键实验)
2
+
3
+ > 适用对象:`stableConversationId`(默认 `false`)开启后由 `deriveStableConversationId(bodyJson)` 生成的值。
4
+ > 本文件是该开关语义的**唯一权威定义**;`CHANGELOG.md` / `docs/DESIGN.md` / 实现注释均须与之一致。
5
+ > 本文不写任何真实账号、机器、路径值;账号一律称「账号A / 账号别名」,本机路径一律 `/Users/<you>`。
6
+
7
+ ## 1. 决策:采用路线 A(最小范围)
8
+
9
+ 保留「从请求正文前缀派生稳定值」的实现,但把它**准确定位为「请求前缀派生的亲和键实验」(affinity-key experiment)**,供使用者在受控条件下对照「稳定 `X-Conversation-ID` 与隐式前缀缓存命中之间的关系」。
10
+
11
+ - 它**不是**宿主 `sessionId`,**不是**官方会话标识,**不是**真正的会话稳定键。
12
+ - 它只是一个由请求内容决定的、在一次连续对话中尽量不变的请求头取值,目的是让「同一不变前缀 + 同一 `X-Conversation-ID`」这一组合可复现,便于单变量对照。
13
+ - 上游内部究竟是「按缓存键分区」「按路由亲和」还是二者混合,本文件及所有相关文档**不做机制断言**;本 PR 也不声称稳定 ID 能改善命中,改善与否须由使用者自行在指定构建/账号/模型/时间窗口下验证。
14
+ - 默认 `stableConversationId` 为 `false`。**默认 `false` 不因任何实验成功自动改变;推广默认值属于单独决策。**
15
+
16
+ 路线 B(真正的会话稳定且互斥隔离,需要可信的宿主会话标识,例如由 DSH 透传 `sessionId`)能做到「整段会话稳定 + 不同会话之间互斥隔离」,但超出本次最小范围:**本次不采用,需另行设计并提交用户确认**。
17
+
18
+ ## 2. 已知限制(路线 A 的固有属性,不是 bug)
19
+
20
+ 1. **纯靠请求正文无法可靠区分正文完全相同的两个独立会话。** 若两个独立会话的「不变前缀」(`model` + 首条 `system` + 第一条真实 `user`)完全相同,它们会**共享同一个派生键**。这是路线 A 的已知限制;文档不得对会话之间的隔离性或互斥性作任何肯定宣称。
21
+ 2. **键可能在会话中途改变**,因为派生自请求内容而非会话身份。以下情况都可能换键:
22
+ - 上下文压缩 / 摘要重写(首条 `system` 或首条真实 `user` 变化);
23
+ - 首条消息被删除、重排,或注入块被当作真实首问;
24
+ - 首问内容变化(用户改写首个问题);
25
+ - 模型切换(`model` 字段变化);
26
+ - 会话分叉 / 恢复 / 重放(前缀被重建)。
27
+ 因此**不得宣传为「整段会话稳定」**,也不得对 warm 轮的命中作确定性宣称。
28
+ 3. **不把本键描述为等价于原生 `sessionId` 的身份**:原生 WorkBuddy 把 `X-Conversation-ID` 绑定为整个会话不变的 `sessionId`;本插件的稳定值派生自请求前缀,二者来源、生命周期、隔离性都不同。
29
+ 4. **UUID 只宣称「符合 v4 形状」**:派生值被格式化成 v4 形状的 UUID 字符串,仅此而已;**不宣称是随机 UUIDv4**,不宣称是加密安全随机,也不宣称是任何官方会话 ID。
30
+
31
+ ## 3. 派生输入的编码规则
32
+
33
+ - 输入元组:`(model, 首条 system, 第一条真实 user)`,跳过宿主注入的 `user` 块;追加的历史、工具调用、回复**不参与哈希**,否则每轮都会变。
34
+ - **NUL 歧义已修**:元组使用**无歧义编码**(JSON 数组),不同元组不会因为字段内出现 NUL 字符(U+0000)或简单拼接而产生相同输入。即三元组(a、b、c)与把 a、b 用 NUL 拼成一个字段的二元组之类不会碰撞。
35
+ - **多模态**:首问含非文本 part(如图片、tool 结果)时,按**规范化完整内容**编码,而不是只取文本片段;**纯图片首问**显式处理——不再隐式忽略非文本 part、不再静默回落到随机 ID。若规范化后仍无法派生(缺字段 / 无法解析),则**显式回退**到每请求现生成,并把该回退路径记入本文件与实现注释。
36
+
37
+ ## 4. 默认关闭与默认值纪律
38
+
39
+ - `stableConversationId` 默认 `false`:默认路径每请求现生成三件套,相对基线 commit `d03282f` 默认路径请求构造逻辑不变(随机 ID 逐次不同;仅相对该基线描述,不覆盖更早版本)。
40
+ - 开启只影响 `X-Conversation-ID`;`X-Conversation-Request-ID` / `X-Conversation-Message-ID` / `X-Root-Request-ID` 仍每请求现生成。
41
+ - 配置在插件挂载时采样一次,改动后需重载插件才生效。
42
+ - **默认 `false` 不因任何实验成功自动改变;推广默认值属于单独决策。**
43
+ - 本 PR 只落地「默认关闭的可选开关 + 派生函数 + 离线 wire 级单测」,**不包含**真实上游实验、安装/重载完整链路验证或 GA 结论;这些属于后续单独工作。
44
+
45
+ ## 5. 结论措辞纪律
46
+
47
+ 本开关是实验性、默认关闭的可选能力,相关叙述一律采用**限定措辞**,不得升级为机制证明或因果宣称:
48
+
49
+ > 在指定构建、账号别名、模型和时间窗口下,观察到稳定 `X-Conversation-ID` 与更高的隐式前缀缓存命中相关。该观察不能区分缓存键分区与路由亲和等内部机制,也不能外推到所有账号/模型;它不构成稳定 ID「导致」命中提升的证明。
50
+
51
+ 以下类别的过强表述一律不得作为结论出现:对 warm 轮命中作确定性宣称、把内部机制当作已证明、把本键描述为等价于宿主会话标识、对会话之间的隔离性或互斥性作肯定宣称、对全部历史版本声称字节级一致、声称控制组排除了全部混淆、把工具输出状态词当作实验证实。
52
+
53
+ 本 PR 不附带任何命中率实测数字;若使用者自行验证,须自行记录条件、限定范围并避免上述过强表述。
54
+
55
+ ## 6. 术语对照
56
+
57
+ | 概念 | 路线 A(本次) | 路线 B(本次不采用) |
58
+ | --- | --- | --- |
59
+ | 键来源 | 请求正文前缀派生 | 可信宿主会话标识(如 `sessionId`) |
60
+ | 定位 | 亲和键实验 / 单变量对照 | 真正的会话稳定键 |
61
+ | 整段会话稳定 | 否(压缩/首问变化/模型切换/分叉都可能换键) | 是(需宿主保证) |
62
+ | 不同会话之间是否互斥隔离 | 否(相同前缀会共享键) | 是 |
63
+ | 是否等价于原生 `sessionId` | 否 | 视实现而定,需单独验证 |
64
+ | 是否需要宿主改动 | 否 | 是(需透传,另行设计 + 用户确认) |
65
+ | 默认值 | `false`,不因实验改变 | 不适用 |
package/lib/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Cn as findWorkbuddyAppExecutableWithSource, F as WorkBuddyCredentialStore, J as workbuddyOwnAuthPath, Mn as resolveDshHome, N as WORKBUDDY_AUTH_FILE_ENV, P as WORKBUDDY_VAULT_DIRNAME, R as defaultDesktopAuthCandidates, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, W as legacyWorkbuddyOwnAuthPath, X as APP_VERSION, Y as workbuddyVaultDir, _n as WORKBUDDY_APP_EXECUTABLE_ENV, a as readHostHeartbeat, b as readDeviceSettings, c as WORKBUDDY_CONNECT_VERSION, d as rosterSeenPath, dn as ensureDeviceSalt, et as DEFAULT_WIRE_PROFILE, f as WORKBUDDY_CN_BASE_ENV, fn as readDeviceSalt, g as createTuringSdk, gn as protectCredentialDirectory, hn as inspectCredentialDirectory, jn as hostPeersInfo, ln as WORKBUDDY_DEVICE_TOKEN_FILE_ENV, m as piAiRuntimeInfo, o as workbuddyHostHeartbeatPath, p as resolveCnGateway, pn as deriveDeviceId, r as isHeartbeatProcessAlive, rt as WorkBuddyUpstreamClient, st as describeRequestHeaderNames, u as describeRosterSeenPayload, un as readDeviceTokenFile, w as FALLBACK_WORKBUDDY_MODELS, z as defaultDesktopAuthDirs } from "./host-heartbeat-1ytBqhSr.js";
2
+ import { F as WorkBuddyCredentialStore, J as workbuddyOwnAuthPath, Mn as hostPeersInfo, N as WORKBUDDY_AUTH_FILE_ENV, Nn as resolveDshHome, P as WORKBUDDY_VAULT_DIRNAME, R as defaultDesktopAuthCandidates, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, W as legacyWorkbuddyOwnAuthPath, X as APP_VERSION, Y as workbuddyVaultDir, _n as protectCredentialDirectory, a as readHostHeartbeat, b as readDeviceSettings, c as WORKBUDDY_CONNECT_VERSION, ct as describeRequestHeaderNames, d as rosterSeenPath, dn as readDeviceTokenFile, et as DEFAULT_WIRE_PROFILE, f as WORKBUDDY_CN_BASE_ENV, fn as ensureDeviceSalt, g as createTuringSdk, gn as inspectCredentialDirectory, m as piAiRuntimeInfo, mn as deriveDeviceId, o as workbuddyHostHeartbeatPath, p as resolveCnGateway, pn as readDeviceSalt, r as isHeartbeatProcessAlive, rt as WorkBuddyUpstreamClient, u as describeRosterSeenPayload, un as WORKBUDDY_DEVICE_TOKEN_FILE_ENV, vn as WORKBUDDY_APP_EXECUTABLE_ENV, w as FALLBACK_WORKBUDDY_MODELS, wn as findWorkbuddyAppExecutableWithSource, z as defaultDesktopAuthDirs } from "./host-heartbeat-BUtle_vT.js";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
  import { realpathSync } from "node:fs";
package/lib/client.js CHANGED
@@ -9182,6 +9182,11 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
9182
9182
  */
9183
9183
  const STATUS_RETRY_BASE_MS = 3e3;
9184
9184
  const STATUS_RETRY_MAX_MS = 3e4;
9185
+ function gateRefusalOf(value) {
9186
+ if (value === null || typeof value !== "object") return void 0;
9187
+ const code = value.error;
9188
+ return code === "host-not-trusted" || code === "origin-not-trusted" ? code : void 0;
9189
+ }
9185
9190
  /**
9186
9191
  * The reasoning tiers the local CodeBuddy CLI accepts for its `--effort` flag.
9187
9192
  *
@@ -9614,6 +9619,17 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
9614
9619
  */
9615
9620
  const [statusByRegion, setStatusByRegion] = (0, react.useState)({});
9616
9621
  /**
9622
+ * The Host's loopback gate refused THIS card's own request (403, issue #261).
9623
+ *
9624
+ * Card-level, not per-region: the gate refuses every plugin route before any
9625
+ * handler runs, so one flag covers both tabs. It is the two codes from
9626
+ * `gateRefusalOf`, not a boolean — the remedies differ (Host authority vs a
9627
+ * foreign page), so the copy has to say which one it is. Kept out of
9628
+ * `statusByRegion` because a refusal is a property of the REQUEST, not of a
9629
+ * region's account state, and a later successful read clears it.
9630
+ */
9631
+ const [gateRefused, setGateRefused] = (0, react.useState)(void 0);
9632
+ /**
9617
9633
  * Which of the card's three sections is on screen.
9618
9634
  *
9619
9635
  * The section tabs exist because the card grew into one 3,500 px column that
@@ -9850,6 +9866,7 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
9850
9866
  const usageGuard = (0, react.useRef)(createLatestWins());
9851
9867
  const refreshUsage = (0, react.useCallback)(async (region, signal) => {
9852
9868
  const stale = usageGuard.current.begin(region);
9869
+ let gateCause;
9853
9870
  try {
9854
9871
  const response = await fetch(withWorkBuddyRegion(WORKBUDDY_USAGE_PATH, region), {
9855
9872
  headers: { accept: "application/json" },
@@ -9857,17 +9874,24 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
9857
9874
  ...signal === void 0 ? {} : { signal }
9858
9875
  });
9859
9876
  const value = await response.json().catch(() => void 0);
9860
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
9877
+ if (!response.ok) {
9878
+ gateCause = gateRefusalOf(value);
9879
+ throw new Error(`HTTP ${response.status}`);
9880
+ }
9861
9881
  const usage = value;
9862
9882
  if (stale()) return void 0;
9863
- if (mounted.current && signal?.aborted !== true) setStatusByRegion((prev) => ({
9864
- ...prev,
9865
- [region]: usage
9866
- }));
9883
+ if (mounted.current && signal?.aborted !== true) {
9884
+ setGateRefused(void 0);
9885
+ setStatusByRegion((prev) => ({
9886
+ ...prev,
9887
+ [region]: usage
9888
+ }));
9889
+ }
9867
9890
  return usage;
9868
9891
  } catch (error) {
9869
9892
  if (stale()) return void 0;
9870
9893
  if (mounted.current && signal?.aborted !== true) {
9894
+ setGateRefused(gateCause);
9871
9895
  const message = error instanceof Error ? error.message : t("row.requestFailed");
9872
9896
  setStatusByRegion((prev) => {
9873
9897
  const previous = prev[region];
@@ -12311,7 +12335,7 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
12311
12335
  className: "dsm-workbuddy-tab-off-notice",
12312
12336
  children: t("row.tabOffNotice")
12313
12337
  }) : null,
12314
- status.status === "error" || status.status === "signed-in" && status.creditsError !== void 0 ? status.status === "signed-in" && status.credentialRejected === true ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12338
+ gateRefused !== void 0 ? null : status.status === "error" || status.status === "signed-in" && status.creditsError !== void 0 ? status.status === "signed-in" && status.credentialRejected === true ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12315
12339
  className: "dsm-workbuddy-usage-hint",
12316
12340
  children: t("row.reloginHint")
12317
12341
  }) : null,
@@ -12868,7 +12892,30 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
12868
12892
  t
12869
12893
  }) : null
12870
12894
  ] }) : null,
12871
- status.status === "error" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12895
+ gateRefused === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12896
+ className: "dsm-workbuddy-usage-error-block",
12897
+ children: [
12898
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12899
+ className: "dsm-workbuddy-usage-error",
12900
+ role: "alert",
12901
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: t("row.usageGateRefusedTitle") })
12902
+ }),
12903
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12904
+ className: "dsm-workbuddy-usage-hint",
12905
+ children: t(gateRefused === "host-not-trusted" ? "row.usageGateHostRefused" : "row.usageGateOriginRefused")
12906
+ }),
12907
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
12908
+ type: "button",
12909
+ className: "dsm-btn dsm-btn-outline",
12910
+ onClick: () => {
12911
+ statusRetries.current = 0;
12912
+ refreshUsage(activeRegion);
12913
+ },
12914
+ children: t("row.usageRetry")
12915
+ })
12916
+ ]
12917
+ }),
12918
+ status.status === "error" && gateRefused === void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
12872
12919
  className: "dsm-workbuddy-usage-error-block",
12873
12920
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
12874
12921
  className: "dsm-workbuddy-usage-error",
@@ -15134,6 +15181,9 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
15134
15181
  "row.requestFailedHint": "Refresh failed — showing the last loaded data: {message}",
15135
15182
  "row.usageErrorHint": "Could not read the account status: {message}. The local DSH service may have just restarted — retrying automatically.",
15136
15183
  "row.usageRetry": "Retry",
15184
+ "row.usageGateRefusedTitle": "The host refused this card's request (HTTP 403)",
15185
+ "row.usageGateHostRefused": "The host did not recognise the address this page was opened from, so it refused the request before the plugin could read anything. This is not a sign-in problem — signing in again will not help. Open DSH at its local address (127.0.0.1) instead of a LAN address or reverse proxy; if you must use that address, add it to this plugin's trustedHosts setting (same authority as the host's --trusted-host).",
15186
+ "row.usageGateOriginRefused": "The host refused the request because the page that sent it came from a different site. Open this card from inside the DSH window itself, not from a bookmark to a mirrored page.",
15137
15187
  "row.poolErrUnavailable": "The account pool is not available in this build (or its batch route is missing). Restart the app; if it persists, the plugin needs reinstalling.",
15138
15188
  "row.poolErrFailed": "The batch failed on the host side: {message}",
15139
15189
  "row.poolErrHttp": "The batch was refused (HTTP {status}). Check the plugin is up to date and try again.",
@@ -15698,6 +15748,9 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
15698
15748
  "row.requestFailedHint": "刷新失败——下方为上次加载的数据:{message}",
15699
15749
  "row.usageErrorHint": "读取账号状态失败:{message}。本地 DSH 服务可能刚重启过,正在自动重试。",
15700
15750
  "row.usageRetry": "重试",
15751
+ "row.usageGateRefusedTitle": "宿主拒绝了这张卡片的请求(HTTP 403)",
15752
+ "row.usageGateHostRefused": "宿主没有认出你打开这个页面所用的地址,因此在插件读到任何数据之前就拒绝了请求。这不是登录问题——重新登录不会有用。请改用本机地址(127.0.0.1)打开 DSH,而不是局域网地址或反向代理;如果必须使用那个地址,请把它加进本插件的 trustedHosts 设置(与宿主的 --trusted-host 填同一个 authority)。",
15753
+ "row.usageGateOriginRefused": "宿主因为发出这个请求的页面来自另一个站点而拒绝了它。请从 DSH 窗口内部打开这张卡片,而不是从镜像页面的书签进入。",
15701
15754
  "row.poolErrUnavailable": "本版本没有可用的账号池(或其批量接口缺失)。请重启应用;若仍不行,插件可能需要重新安装。",
15702
15755
  "row.poolErrFailed": "批量操作在宿主侧失败:{message}",
15703
15756
  "row.poolErrHttp": "批量操作被拒绝(HTTP {status})。请确认插件是最新版本后重试。",
@@ -4445,12 +4445,21 @@ function commonHeaders(credential, identity = {}) {
4445
4445
  * extras is satisfied by the triple without it. Hence exactly three.
4446
4446
  *
4447
4447
  * VALUES. The gateway does not verify where these ids come from — any well-formed
4448
- * UUID passes — so nothing here is a secret and nothing is persisted. They are
4449
- * still freshly generated per request, as the official client generates
4450
- * its own per call: reusing one value across requests would forge a
4451
- * conversation identity the plugin does not actually have, and the first thing
4452
- * that would break is the upstream's own correlation of a session it is being
4453
- * told about twice under one id.
4448
+ * UUID passes — so nothing here is a secret and nothing is persisted.
4449
+ *
4450
+ * DEFAULT: `X-Conversation-ID` is freshly generated per request, like the other
4451
+ * two ids. That is the shape the gate was bisected with and the shape the tests
4452
+ * below pin; it is also the shape the plugin has always sent on this path. There
4453
+ * is an OPT-IN A/B mode (`stableConversationId`, see
4454
+ * {@link deriveStableConversationId}) that instead pins a v4-SHAPED value derived
4455
+ * from the request's stable prefix — a prefix-derived AFFINITY KEY, not a host
4456
+ * session id. Only `X-Conversation-ID` is pinned: the request, message and root
4457
+ * ids stay per-request. This switch exists for an offline single-variable hit-rate
4458
+ * comparison; it makes NO claim about how the upstream keys or partitions any
4459
+ * cache, and it does not prove that stable ids improve anything. The mode is OFF
4460
+ * by default — enabling it changes a byte the gateway sees, and a hypothesis is
4461
+ * not a reason to change the default shape for every account before it has been
4462
+ * measured. See docs/STABLE-KEY-SEMANTICS.md.
4454
4463
  *
4455
4464
  * APPLIED TO BOTH REGIONS on purpose. The CN gateway tolerates their absence
4456
4465
  * today, so this is harmless there — and a header that is only ever sent on one
@@ -4458,15 +4467,17 @@ function commonHeaders(credential, identity = {}) {
4458
4467
  * from the CN side. One code path, both regions.
4459
4468
  *
4460
4469
  * @returns the three headers (four when the usage identity is on, which adds
4461
- * `X-Request-ID`), every value distinct.
4470
+ * `X-Request-ID`). By default every value is distinct and fresh; in the opt-in
4471
+ * stable mode only `X-Conversation-ID` is pinned to a prefix-derived affinity
4472
+ * key for requests sharing that prefix (see {@link deriveStableConversationId}).
4462
4473
  */
4463
- function conversationHeaders(shape, identity = {}) {
4474
+ function conversationHeaders(shape, identity = {}, stableConversationId) {
4464
4475
  const officialIds = shape === "chat" && identity.usageIdentity === true;
4465
4476
  const id = officialIds ? uuidv7 : randomUUID;
4466
4477
  const messageId = id();
4467
4478
  const conversationRequestId = id();
4468
4479
  return {
4469
- "X-Conversation-ID": id(),
4480
+ "X-Conversation-ID": stableConversationId ?? id(),
4470
4481
  "X-Conversation-Request-ID": conversationRequestId,
4471
4482
  ...profileOf(identity) === "balanced" ? { "X-Root-Request-ID": conversationRequestId } : {},
4472
4483
  "X-Conversation-Message-ID": messageId,
@@ -4489,8 +4500,10 @@ function conversationHeaders(shape, identity = {}) {
4489
4500
  * Only the FORMAT is aligned, never the value's meaning: the timestamp prefix
4490
4501
  * is the moment this request was generated, which is exactly what a v7 id is
4491
4502
  * for. It is NOT a claim that these ids correlate with an official session —
4492
- * the plugin still generates a fresh identity per request (see
4493
- * {@link conversationHeaders}).
4503
+ * by default the plugin still generates a fresh identity per request (see
4504
+ * {@link conversationHeaders}); the opt-in stable mode pins only
4505
+ * `X-Conversation-ID` to a prefix-derived affinity key built with
4506
+ * {@link deriveStableConversationId}, never to a host session id.
4494
4507
  */
4495
4508
  function uuidv7(nowMs = Date.now()) {
4496
4509
  const bytes = randomBytes(16);
@@ -4500,6 +4513,118 @@ function uuidv7(nowMs = Date.now()) {
4500
4513
  return bytes.toString("hex");
4501
4514
  }
4502
4515
  /**
4516
+ * Format the first 32 hex chars of a digest as a hyphenated, v4-SHAPED value:
4517
+ * the version nibble and variant bits are overwritten so the string matches the
4518
+ * RFC-4122 v4 layout. This is a shape claim only — the bytes come from a SHA-256
4519
+ * digest, so this is NOT a random UUIDv4 and NOT an official session id.
4520
+ */
4521
+ function formatAsUuidV4(hex) {
4522
+ const chars = hex.slice(0, 32).split("");
4523
+ chars[12] = "4";
4524
+ chars[16] = [
4525
+ "8",
4526
+ "9",
4527
+ "a",
4528
+ "b"
4529
+ ][Number.parseInt(chars[16], 16) % 4];
4530
+ return `${chars.slice(0, 8).join("")}-${chars.slice(8, 12).join("")}-${chars.slice(12, 16).join("")}-${chars.slice(16, 20).join("")}-${chars.slice(20, 32).join("")}`;
4531
+ }
4532
+ /** Version tag for the affinity-key encoding, so a future scheme change is explicit. */
4533
+ const STABLE_KEY_SCHEME = "dsh-stable-conversation-id/v1";
4534
+ /** Canonical keys meaning "no usable content" — these must fall back to a fresh id. */
4535
+ const EMPTY_CANONICAL_KEYS = /* @__PURE__ */ new Set([
4536
+ "null",
4537
+ "\"\"",
4538
+ "[]",
4539
+ "{}"
4540
+ ]);
4541
+ /**
4542
+ * A deterministic deep value for hashing: object keys sorted, array order kept,
4543
+ * `undefined` (which JSON.stringify would otherwise drop) normalized to `null`.
4544
+ * Returns a FRESH structure, so callers may mutate it without touching the body.
4545
+ */
4546
+ function canonicalize(value) {
4547
+ if (Array.isArray(value)) return value.map(canonicalize);
4548
+ if (typeof value === "object" && value !== null) {
4549
+ const record = value;
4550
+ const sorted = {};
4551
+ for (const key of Object.keys(record).sort()) sorted[key] = canonicalize(record[key]);
4552
+ return sorted;
4553
+ }
4554
+ return value === void 0 ? null : value;
4555
+ }
4556
+ /**
4557
+ * Complete, canonical encoding of one message's `content` for the affinity key.
4558
+ * Unlike {@link textOfContent} (prefix matching only, which drops non-text parts)
4559
+ * this keeps EVERY part, so a pure-image first user and two bodies differing only
4560
+ * in their image bytes are distinguished rather than silently ignored. The
4561
+ * leading ACP tag on the first text part is stripped, since it carries a
4562
+ * per-request message number. Operates on a clone from {@link canonicalize}, so
4563
+ * the request body is never mutated.
4564
+ */
4565
+ function canonicalContentKey(content, stripAcp) {
4566
+ const canonical = canonicalize(content);
4567
+ const value = stripAcp ? stripLeadingAcpTag(canonical).value : canonical;
4568
+ return JSON.stringify(value);
4569
+ }
4570
+ /**
4571
+ * Derive a request-prefix AFFINITY KEY and return it in `X-Conversation-ID` shape.
4572
+ *
4573
+ * ROUTE A / OPT-IN EXPERIMENT (`stableConversationId`, default off). This is a
4574
+ * prefix-derived affinity key, not a host session id: the value hashes the model
4575
+ * id, the first `system` message's FULL content and the FIRST REAL `user`
4576
+ * message's FULL content (skipping the harness's injected context blocks via
4577
+ * {@link injectedPrefixPattern}). Appended history, tool calls and assistant
4578
+ * replies are deliberately NOT part of the key — they grow every turn.
4579
+ *
4580
+ * Known limits, documented in `docs/STABLE-KEY-SEMANTICS.md`: two independent
4581
+ * sessions with an identical prefix SHARE this key; compression, first-message
4582
+ * edits, model switches or session forks may change the key; the value only
4583
+ * claims a v4-shaped layout, never equality with a native `sessionId`. No claim
4584
+ * is made about the upstream's internal mechanism — cache-key partitioning vs
4585
+ * routing affinity are indistinguishable from the client side.
4586
+ *
4587
+ * Encoding: the prefix fields are fed to SHA-256 as a JSON array, so an embedded
4588
+ * U+0000 cannot make two distinct tuples collide; each message's FULL content is
4589
+ * canonicalized (object keys sorted, non-text parts kept), so a pure-image first
4590
+ * user and two bodies differing only in image bytes are handled explicitly. A
4591
+ * body that is not parseable chat JSON, or lacks a usable model / system / first
4592
+ * real user, yields `undefined` and the caller falls back to the fresh per-request
4593
+ * id. No secret, account or machine value is read here.
4594
+ */
4595
+ function deriveStableConversationId(bodyJson) {
4596
+ let parsed;
4597
+ try {
4598
+ parsed = JSON.parse(bodyJson);
4599
+ } catch {
4600
+ return;
4601
+ }
4602
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
4603
+ const body = parsed;
4604
+ const model = typeof body["model"] === "string" ? body["model"] : "";
4605
+ const messages = body["messages"];
4606
+ if (model === "" || !Array.isArray(messages)) return void 0;
4607
+ let systemKey;
4608
+ let firstRealUserKey;
4609
+ const injected = injectedPrefixPattern();
4610
+ for (const value of messages) {
4611
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
4612
+ const message = value;
4613
+ const role = message["role"];
4614
+ if (role === "system" && systemKey === void 0) systemKey = canonicalContentKey(message["content"], false);
4615
+ if (role === "user" && firstRealUserKey === void 0 && !isInjectedUserMessage(message, injected)) firstRealUserKey = canonicalContentKey(message["content"], true);
4616
+ }
4617
+ if (systemKey === void 0 || EMPTY_CANONICAL_KEYS.has(systemKey)) return void 0;
4618
+ if (firstRealUserKey === void 0 || EMPTY_CANONICAL_KEYS.has(firstRealUserKey)) return void 0;
4619
+ const tuple = JSON.stringify([
4620
+ STABLE_KEY_SCHEME,
4621
+ model,
4622
+ systemKey,
4623
+ firstRealUserKey
4624
+ ]);
4625
+ return formatAsUuidV4(createHash("sha256").update(tuple).digest("hex"));
4626
+ }
4627
+ /**
4503
4628
  * 没有显式配置时用的档位。
4504
4629
  *
4505
4630
  * `balanced`:P0.5 已证实有效,默认就应该吃到收益;`conservative` 留给
@@ -4610,7 +4735,7 @@ async function resolveWireIdentity(identity) {
4610
4735
  };
4611
4736
  }
4612
4737
  /** Chat request headers, including the X-No-* conventions the official CLI uses. */
4613
- function chatHeaders(credential, identity = {}) {
4738
+ function chatHeaders(credential, identity = {}, stableConversationId) {
4614
4739
  return {
4615
4740
  ...commonHeaders(credential, identity),
4616
4741
  "Content-Type": "application/json",
@@ -4619,7 +4744,7 @@ function chatHeaders(credential, identity = {}) {
4619
4744
  ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
4620
4745
  ...attributionHeaders(identity),
4621
4746
  ...deviceHeaders(credential, identity),
4622
- ...conversationHeaders("chat", identity)
4747
+ ...conversationHeaders("chat", identity, stableConversationId)
4623
4748
  };
4624
4749
  }
4625
4750
  /**
@@ -6815,8 +6940,9 @@ var WorkBuddyUpstreamClient = class {
6815
6940
  async chatStream(credential, bodyJson, signal) {
6816
6941
  let response;
6817
6942
  try {
6943
+ const identity = await this.wireIdentity(credential);
6818
6944
  const headers = {
6819
- ...chatHeaders(credential, await this.wireIdentity(credential)),
6945
+ ...chatHeaders(credential, identity, identity.stableConversationId === true ? deriveStableConversationId(bodyJson) : void 0),
6820
6946
  "Authorization": `Bearer ${credential.accessToken}`
6821
6947
  };
6822
6948
  if (signal?.aborted === true) return {
@@ -11113,7 +11239,7 @@ function describeRosterSeenPayload(raw) {
11113
11239
  //#endregion
11114
11240
  //#region src/version.ts
11115
11241
  /** The npm package version this build was produced from. */
11116
- const WORKBUDDY_CONNECT_VERSION = "5.24.6";
11242
+ const WORKBUDDY_CONNECT_VERSION = "5.24.8";
11117
11243
  //#endregion
11118
11244
  //#region src/host-heartbeat.ts
11119
11245
  /**
@@ -11347,4 +11473,4 @@ async function clearHostHeartbeat(owner) {
11347
11473
  if (current === owner.contents) await rm(owner.path, { force: true });
11348
11474
  }
11349
11475
  //#endregion
11350
- export { CREDENTIAL_REJECTED_CODE as $, isWatermarkFreeImageModel as $t, withoutRouters as A, workbuddyAppExecutableCandidates as An, REFUSES_OFF_MODEL_IDS as At, defaultDesktopAuthPath as B, parseSupportedSecondsRange as Bt, setDeviceMode as C, findWorkbuddyAppExecutableWithSource as Cn, regionOf as Ct, applyContextBudgets as D, macosNestedAppBundles as Dn, attachBusyLevels as Dt, WorkBuddyCatalog as E, macosBundleExecutable as En, toolSchemaRejectAdvice as Et, WorkBuddyCredentialStore as F, recordRefusal as Ft, parseWorkBuddyAuth as G, IMAGE_TAG_TEXT_TO_IMAGE as Gt, isEncryptedCredentialError as H, resolveVideoParams as Ht, WorkBuddyEncryptedCredentialError as I, withEffectiveOff as It, workbuddyOwnAuthPath as J, imageDataUrl as Jt, preferredAccountName as K, MAX_INPUT_IMAGE_BYTES as Kt, authFileName as L, VIDEO_TAG_IMAGE_TO_VIDEO as Lt, WORKBUDDY_AUTH_FILENAME as M, resolveDshHome as Mn, lastRefusalFor as Mt, WORKBUDDY_AUTH_FILE_ENV as N, withFileLock as Nn, offDefaultFor as Nt, deriveCatalog as O, openEncryptedField as On, promoBadgeTone as Ot, WORKBUDDY_VAULT_DIRNAME as P, writeFileAtomic as Pn, offRefused as Pt, CONTEXT_OVERFLOW_MARKER as Q, isBareBase64Image as Qt, defaultDesktopAuthCandidates as R, VIDEO_TAG_TEXT_TO_VIDEO as Rt, saveDeviceSdkSettings as S, findWorkbuddyAppExecutable as Sn, prepareChatBody as St, FALLBACK_WORKBUDDY_MODELS_GLOBAL as T, isWorkbuddyBundle as Tn, rewriteSessionTitleModel as Tt, isVaultAccountId as U, IMAGE_SIZE_LIMITS_WIDE as Ut, hasEncryptedCredentialFields as V, pickVideoModel as Vt, legacyWorkbuddyOwnAuthPath as W, IMAGE_TAG_IMAGE_TO_IMAGE as Wt, APP_VERSION as X, imageModelChoices as Xt, workbuddyVaultDir as Y, imageMimeForPath as Yt, BODY_OVERSIZE_MARKER as Z, imageSizeLimitsOf as Zt, createDeviceProfileLookup as _, WORKBUDDY_APP_EXECUTABLE_ENV as _n, openingEvidenceOfBody as _t, readHostHeartbeat as a, pruneTempDir as an, classifyUpstreamError as at, readDeviceSettings as b, deriveAtRestKeyId as bn, parseUpstreamModel as bt, WORKBUDDY_CONNECT_VERSION as c, nativeModalityOf as cn, forceNeutralHead as ct, rosterSeenPath as d, ensureDeviceSalt as dn, isConversationIdGateBody as dt, parseImageDataUrl as en, DEFAULT_WIRE_PROFILE as et, WORKBUDDY_CN_BASE_ENV as f, readDeviceSalt as fn, isCredentialRejectedError as ft, createTuringSdk as g, protectCredentialDirectory as gn, modelIdOfBody as gt, createDeviceSdkPort as h, inspectCredentialDirectory as hn, knownRegionOf as ht, processStartTimeMs as i, queueNoticeText as in, channelGateMemberOf as it, ENCRYPTED_CREDENTIAL_CODE as j, hostPeersInfo as jn, defaultOffModelIds as jt, fallbackModelsFor as k, readAtRestKey as kn, selectPromoBadge as kt, createFileRosterSeenStore as l, WORKBUDDY_DEVICE_TOKEN_FILE_ENV as ln, isBodyOversizeRefusal as lt, piAiRuntimeInfo as m, isDeviceId as mn, isToolSchemaRejectBody as mt, clearHostHeartbeat as n, sniffImageMime as nn, WorkBuddyCredentialRejectedError as nt, workbuddyHostHeartbeatPath as o, NATIVE_MODALITY_BY_MODEL_ID as on, declaredTools as ot, resolveCnGateway as p, deriveDeviceId as pn, isFirstMessageGateBody as pt, workbuddyAccountId as q, WorkBuddyImageError as qt, isHeartbeatProcessAlive as r, parseQueueAnswer as rn, WorkBuddyUpstreamClient as rt, writeHostHeartbeat as s, imageDefaultFor as sn, describeRequestHeaderNames as st, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, pickMediaModel as tn, WORKBUDDY_FALLBACK_SYSTEM_PROMPT as tt, describeRosterSeenPayload as u, readDeviceTokenFile as un, isContextTooLongBody as ut, describeDerivedDevices as v, clearAtRestKeyCache as vn, parseCreditMultiplier as vt, FALLBACK_WORKBUDDY_MODELS as w, isEncryptedFieldWrapper as wn, requestEvidenceOf as wt, saveDeviceProfile as x, fetchAtRestKeyPayload as xn, perturbChannelFingerprints as xt, isDeviceMode as y, deriveAtRestKey as yn, parseReasoning as yt, defaultDesktopAuthDirs as z, WorkBuddyVideoError as zt };
11476
+ export { CREDENTIAL_REJECTED_CODE as $, isBareBase64Image as $t, withoutRouters as A, readAtRestKey as An, selectPromoBadge as At, defaultDesktopAuthPath as B, WorkBuddyVideoError as Bt, setDeviceMode as C, findWorkbuddyAppExecutable as Cn, prepareChatBody as Ct, applyContextBudgets as D, macosBundleExecutable as Dn, toolSchemaRejectAdvice as Dt, WorkBuddyCatalog as E, isWorkbuddyBundle as En, rewriteSessionTitleModel as Et, WorkBuddyCredentialStore as F, writeFileAtomic as Fn, offRefused as Ft, parseWorkBuddyAuth as G, IMAGE_TAG_IMAGE_TO_IMAGE as Gt, isEncryptedCredentialError as H, pickVideoModel as Ht, WorkBuddyEncryptedCredentialError as I, recordRefusal as It, workbuddyOwnAuthPath as J, WorkBuddyImageError as Jt, preferredAccountName as K, IMAGE_TAG_TEXT_TO_IMAGE as Kt, authFileName as L, withEffectiveOff as Lt, WORKBUDDY_AUTH_FILENAME as M, hostPeersInfo as Mn, defaultOffModelIds as Mt, WORKBUDDY_AUTH_FILE_ENV as N, resolveDshHome as Nn, lastRefusalFor as Nt, deriveCatalog as O, macosNestedAppBundles as On, attachBusyLevels as Ot, WORKBUDDY_VAULT_DIRNAME as P, withFileLock as Pn, offDefaultFor as Pt, CONTEXT_OVERFLOW_MARKER as Q, imageSizeLimitsOf as Qt, defaultDesktopAuthCandidates as R, VIDEO_TAG_IMAGE_TO_VIDEO as Rt, saveDeviceSdkSettings as S, fetchAtRestKeyPayload as Sn, perturbChannelFingerprints as St, FALLBACK_WORKBUDDY_MODELS_GLOBAL as T, isEncryptedFieldWrapper as Tn, requestEvidenceOf as Tt, isVaultAccountId as U, resolveVideoParams as Ut, hasEncryptedCredentialFields as V, parseSupportedSecondsRange as Vt, legacyWorkbuddyOwnAuthPath as W, IMAGE_SIZE_LIMITS_WIDE as Wt, APP_VERSION as X, imageMimeForPath as Xt, workbuddyVaultDir as Y, imageDataUrl as Yt, BODY_OVERSIZE_MARKER as Z, imageModelChoices as Zt, createDeviceProfileLookup as _, protectCredentialDirectory as _n, modelIdOfBody as _t, readHostHeartbeat as a, queueNoticeText as an, classifyUpstreamError as at, readDeviceSettings as b, deriveAtRestKey as bn, parseReasoning as bt, WORKBUDDY_CONNECT_VERSION as c, imageDefaultFor as cn, describeRequestHeaderNames as ct, rosterSeenPath as d, readDeviceTokenFile as dn, isContextTooLongBody as dt, isWatermarkFreeImageModel as en, DEFAULT_WIRE_PROFILE as et, WORKBUDDY_CN_BASE_ENV as f, ensureDeviceSalt as fn, isConversationIdGateBody as ft, createTuringSdk as g, inspectCredentialDirectory as gn, knownRegionOf as gt, createDeviceSdkPort as h, isDeviceId as hn, isToolSchemaRejectBody as ht, processStartTimeMs as i, parseQueueAnswer as in, channelGateMemberOf as it, ENCRYPTED_CREDENTIAL_CODE as j, workbuddyAppExecutableCandidates as jn, REFUSES_OFF_MODEL_IDS as jt, fallbackModelsFor as k, openEncryptedField as kn, promoBadgeTone as kt, createFileRosterSeenStore as l, nativeModalityOf as ln, forceNeutralHead as lt, piAiRuntimeInfo as m, deriveDeviceId as mn, isFirstMessageGateBody as mt, clearHostHeartbeat as n, pickMediaModel as nn, WorkBuddyCredentialRejectedError as nt, workbuddyHostHeartbeatPath as o, pruneTempDir as on, declaredTools as ot, resolveCnGateway as p, readDeviceSalt as pn, isCredentialRejectedError as pt, workbuddyAccountId as q, MAX_INPUT_IMAGE_BYTES as qt, isHeartbeatProcessAlive as r, sniffImageMime as rn, WorkBuddyUpstreamClient as rt, writeHostHeartbeat as s, NATIVE_MODALITY_BY_MODEL_ID as sn, deriveStableConversationId as st, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, parseImageDataUrl as tn, WORKBUDDY_FALLBACK_SYSTEM_PROMPT as tt, describeRosterSeenPayload as u, WORKBUDDY_DEVICE_TOKEN_FILE_ENV as un, isBodyOversizeRefusal as ut, describeDerivedDevices as v, WORKBUDDY_APP_EXECUTABLE_ENV as vn, openingEvidenceOfBody as vt, FALLBACK_WORKBUDDY_MODELS as w, findWorkbuddyAppExecutableWithSource as wn, regionOf as wt, saveDeviceProfile as x, deriveAtRestKeyId as xn, parseUpstreamModel as xt, isDeviceMode as y, clearAtRestKeyCache as yn, parseCreditMultiplier as yt, defaultDesktopAuthDirs as z, VIDEO_TAG_TEXT_TO_VIDEO as zt };
package/lib/index.d.ts CHANGED
@@ -1620,6 +1620,32 @@ declare function regionOf(domain: string): WorkBuddyRegion;
1620
1620
  * the same decision as admitting `workbuddy.cn`.
1621
1621
  */
1622
1622
  declare function knownRegionOf(domain: string): WorkBuddyRegion | undefined;
1623
+ /**
1624
+ * Derive a request-prefix AFFINITY KEY and return it in `X-Conversation-ID` shape.
1625
+ *
1626
+ * ROUTE A / OPT-IN EXPERIMENT (`stableConversationId`, default off). This is a
1627
+ * prefix-derived affinity key, not a host session id: the value hashes the model
1628
+ * id, the first `system` message's FULL content and the FIRST REAL `user`
1629
+ * message's FULL content (skipping the harness's injected context blocks via
1630
+ * {@link injectedPrefixPattern}). Appended history, tool calls and assistant
1631
+ * replies are deliberately NOT part of the key — they grow every turn.
1632
+ *
1633
+ * Known limits, documented in `docs/STABLE-KEY-SEMANTICS.md`: two independent
1634
+ * sessions with an identical prefix SHARE this key; compression, first-message
1635
+ * edits, model switches or session forks may change the key; the value only
1636
+ * claims a v4-shaped layout, never equality with a native `sessionId`. No claim
1637
+ * is made about the upstream's internal mechanism — cache-key partitioning vs
1638
+ * routing affinity are indistinguishable from the client side.
1639
+ *
1640
+ * Encoding: the prefix fields are fed to SHA-256 as a JSON array, so an embedded
1641
+ * U+0000 cannot make two distinct tuples collide; each message's FULL content is
1642
+ * canonicalized (object keys sorted, non-text parts kept), so a pure-image first
1643
+ * user and two bodies differing only in image bytes are handled explicitly. A
1644
+ * body that is not parseable chat JSON, or lacks a usable model / system / first
1645
+ * real user, yields `undefined` and the caller falls back to the fresh per-request
1646
+ * id. No secret, account or machine value is read here.
1647
+ */
1648
+ declare function deriveStableConversationId(bodyJson: string): string | undefined;
1623
1649
  /**
1624
1650
  * 出站身份档位(`docs/DEVICE-IDENTITY-AUDIT.md` 的 P1)。
1625
1651
  *
@@ -1656,6 +1682,23 @@ interface WorkBuddyWireIdentity {
1656
1682
  * are untouched either way.
1657
1683
  */
1658
1684
  usageIdentity?: boolean;
1685
+ /**
1686
+ * 请求前缀亲和键 A/B 开关(`chatStream` 专用,默认关,路线 A)。
1687
+ *
1688
+ * 开启后 {@link deriveStableConversationId} 从请求体**不变前缀**派生一个
1689
+ * v4 形状的 `X-Conversation-ID`;其余三件套仍是每请求现生成。默认关闭时
1690
+ * 派生函数不运行、`chatHeaders` 收到 `undefined`,因此不进入稳定键分支。
1691
+ *
1692
+ * 这是**只改一个变量**的离线对照实验,见 `docs/STABLE-KEY-SEMANTICS.md`:
1693
+ * 该值是从请求正文派生的亲和键,不是宿主 `sessionId`,不宣称会话隔离,也
1694
+ * 不证明上游按会话分区或具备路由亲和等内部机制。相同前缀的独立会话会共享
1695
+ * 同一个键,压缩 / 首问变化 / 模型切换都可能换键。客户端无法区分缓存键分区
1696
+ * 与路由亲和,因此这里只做可观测的命中率对照,不做机制断言。
1697
+ *
1698
+ * 默认 `false` 是单独决策,不因任何实验成功自动改变;推广默认值需用户另行
1699
+ * 确认。配置文件里的开关由使用者按 `onUpstreamUsage` 的命中率自行决定。
1700
+ */
1701
+ stableConversationId?: boolean;
1659
1702
  /**
1660
1703
  * 出站头档位,缺省 {@link DEFAULT_WIRE_PROFILE}。
1661
1704
  *
@@ -5369,6 +5412,20 @@ interface WorkBuddyStatusRouteOptions {
5369
5412
  * transfer section (an older bundle keeps rendering, minus the buttons).
5370
5413
  */
5371
5414
  transfer?: WorkBuddyTransferDeps;
5415
+ /**
5416
+ * Authorities the deployer declared trusted for these routes (issue #261).
5417
+ *
5418
+ * A FUNCTION, not a value: the field lives in a volatile config slot, so the
5419
+ * gate must read it at REQUEST time — sampling once at mount would leave a
5420
+ * user who adds an authority behind a proxy with a card that stays 403 until a
5421
+ * full plugin reload, the very reload every other volatile switch here avoids.
5422
+ *
5423
+ * OPTIONAL, and absent reads as "no grants", so a Host that predates the
5424
+ * setting and the entire existing test suite keep the pre-#261 fence exactly.
5425
+ * See `src/loopback.ts` for why the decision is made on the whole authority
5426
+ * (port included) and why the same value drives BOTH the Host and Origin halves.
5427
+ */
5428
+ trustedHosts?(): readonly string[];
5372
5429
  }
5373
5430
  /**
5374
5431
  * What the transfer route needs from the Host. Everything is region-scoped:
@@ -6100,6 +6157,11 @@ interface Config {
6100
6157
  * 本插件未复现的显示对齐,不该成为某个账号开始失败的理由。
6101
6158
  */
6102
6159
  usageIdentity?: boolean;
6160
+ /**
6161
+ * 会话 id 稳定化 A/B 开关,默认关;详见配置项 description 与 upstream.ts。
6162
+ * 开启后只固定 X-Conversation-ID,其余三件套仍每请求现生成。
6163
+ */
6164
+ stableConversationId?: boolean;
6103
6165
  /**
6104
6166
  * Move the harness's injected context above the real prompt (issue #132).
6105
6167
  *
@@ -6203,6 +6265,13 @@ interface Config {
6203
6265
  */
6204
6266
  text?: string;
6205
6267
  };
6268
+ /**
6269
+ * 部署方为插件自身路由声明的可信 authority(issue #261)。默认空,见下方
6270
+ * schema 的说明:反代后面 DSH 绑回环、Host 是公网地址,插件的 Host/Origin
6271
+ * 闸门会全部 403;加一条白名单让宿主与插件对同一个 Host 的判定一致。
6272
+ * 元素是裸 `host[:port]`,在挂载时逐条校验;请求时读取,改动无需重载。
6273
+ */
6274
+ trustedHosts?: string[];
6206
6275
  }
6207
6276
  /**
6208
6277
  * Mark a schema's field as volatile on the DSH lines that support it.
@@ -6345,4 +6414,4 @@ declare function legacyAttributionRegion(value: Config, accountsFor: (region: Wo
6345
6414
  */
6346
6415
  declare function apply(ctx: Context, config: Config): void;
6347
6416
  //#endregion
6348
- export { CREDENTIAL_REJECTED_CODE, Config, DEFAULT_PROBE_INPUT_TOKENS, ENCRYPTED_CREDENTIAL_CODE, FALLBACK_WORKBUDDY_MODELS, FALLBACK_WORKBUDDY_MODELS_GLOBAL, NATIVE_MODALITY_BY_MODEL_ID, PROBE_INPUT_TOKEN_CHOICES, PROBE_MAX_TOKENS, PROBE_SYSTEM_PROMPT, REFUSES_OFF_MODEL_IDS, type UpstreamErrorKind, WORKBUDDY_ACCOUNTS_REFRESH_PATH, WORKBUDDY_APP_EXECUTABLE_ENV, WORKBUDDY_AUTH_FILENAME, WORKBUDDY_AUTH_FILE_ENV, WORKBUDDY_CHECKIN_PATH, WORKBUDDY_CONNECT_VERSION, WORKBUDDY_GLOBAL_PROVIDER, WORKBUDDY_HOST_HEARTBEAT_FILENAME, WORKBUDDY_MODELS_REFRESH_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_PROVIDER, WORKBUDDY_PROVIDERS, WORKBUDDY_PROVIDER_DISPLAY_NAMES, WORKBUDDY_REGIONS, WORKBUDDY_REGION_PARAM, WORKBUDDY_SETTINGS_NS, WORKBUDDY_STREAM_IDLE_TIMEOUT_MS, WORKBUDDY_TPS_PATH, WORKBUDDY_USAGE_PATH, type WorkBuddyAccountChoice, type WorkBuddyAdapter, type WorkBuddyAuthStatus, type WorkBuddyCandidateFailure, WorkBuddyCatalog, type WorkBuddyChatResult, type WorkBuddyCredential, type WorkBuddyCredentialRecovery, WorkBuddyCredentialRejectedError, WorkBuddyCredentialStore, type WorkBuddyCreditPackage, type WorkBuddyCredits, WorkBuddyEncryptedCredentialError, type WorkBuddyEncryptedField, type WorkBuddyHostHeartbeat, type WorkBuddyHostHeartbeatOwner, type WorkBuddyModelInfo, type WorkBuddyNativeModality, WorkBuddyPoolPreferences, type WorkBuddyProbeClient, type WorkBuddyProbeOutcome, type WorkBuddyProbeResult, type WorkBuddyProbeStore, type WorkBuddyReasoning, type WorkBuddyRecoveryCandidate, type WorkBuddyRefreshOutcome, WorkBuddyRegionState, type WorkBuddyShim, type WorkBuddyStatusRouteOptions, type WorkBuddyStoreOptions, WorkBuddyUpstreamClient, type WorkBuddyUpstreamModel, type WorkBuddyUsabilityProbeOptions, apply, asVolatile, authFileName, classifyUpstreamError, clearAtRestKeyCache, clearHostHeartbeat, cooldownOf, createAccountUsabilityProbe, createWorkBuddyAdapter, createWorkBuddyShim, creditOfStream, defaultDesktopAuthCandidates, defaultDesktopAuthDirs, defaultDesktopAuthPath, defaultOffModelIds, deriveAtRestKey, deriveAtRestKeyId, deriveCatalog, fallbackModelsFor, fetchAtRestKeyPayload, findWorkbuddyAppExecutable, hasEncryptedCredentialFields, imageDefaultFor, imageToolRegionOf, inject, isCredentialRejectedError, isEncryptedCredentialError, isEncryptedFieldWrapper, isHeartbeatProcessAlive, isWorkbuddyBundle, knownRegionOf, legacyAttributionRegion, legacyWorkbuddyOwnAuthPath, macosBundleExecutable, macosNestedAppBundles, modelIdOfBody, name, nativeModalityOf, nextRegionEnabled, nextRegionSlots, offDefaultFor, openEncryptedField, outcomeOfFailure, parseCreditMultiplier, parseReasoning, parseRetryAfter, parseUpstreamModel, parseWorkBuddyAuth, prepareChatBody, probeModel, probeRequestBody, probeSucceeded, processStartTimeMs, readAtRestKey, readHostHeartbeat, realTierAvailabilityFor, regionCleared, regionEnabled, regionEnabledOf, regionOf, regionOfProvider, regionOfStatusUrl, regionStateOf, regionsFieldIsCorrupt, regionsMapOf, registerWorkBuddyStatusRoute, resolveCredentialRecovery, selectAccountFor, settingsNamespaceOf, toPersistedWorkBuddyModel, unwrapVolatileDeep, videoToolRegionOf, withEffectiveOff, withWorkBuddyRegion, workBuddyDisplayName, workBuddyModelInput, workBuddyThinkingLevelMap, workBuddyWebStatus, workbuddyAccountId, workbuddyAppExecutableCandidates, workbuddyHostHeartbeatPath, workbuddyOwnAuthPath, writeHostHeartbeat };
6417
+ export { CREDENTIAL_REJECTED_CODE, Config, DEFAULT_PROBE_INPUT_TOKENS, ENCRYPTED_CREDENTIAL_CODE, FALLBACK_WORKBUDDY_MODELS, FALLBACK_WORKBUDDY_MODELS_GLOBAL, NATIVE_MODALITY_BY_MODEL_ID, PROBE_INPUT_TOKEN_CHOICES, PROBE_MAX_TOKENS, PROBE_SYSTEM_PROMPT, REFUSES_OFF_MODEL_IDS, type UpstreamErrorKind, WORKBUDDY_ACCOUNTS_REFRESH_PATH, WORKBUDDY_APP_EXECUTABLE_ENV, WORKBUDDY_AUTH_FILENAME, WORKBUDDY_AUTH_FILE_ENV, WORKBUDDY_CHECKIN_PATH, WORKBUDDY_CONNECT_VERSION, WORKBUDDY_GLOBAL_PROVIDER, WORKBUDDY_HOST_HEARTBEAT_FILENAME, WORKBUDDY_MODELS_REFRESH_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_PROVIDER, WORKBUDDY_PROVIDERS, WORKBUDDY_PROVIDER_DISPLAY_NAMES, WORKBUDDY_REGIONS, WORKBUDDY_REGION_PARAM, WORKBUDDY_SETTINGS_NS, WORKBUDDY_STREAM_IDLE_TIMEOUT_MS, WORKBUDDY_TPS_PATH, WORKBUDDY_USAGE_PATH, type WorkBuddyAccountChoice, type WorkBuddyAdapter, type WorkBuddyAuthStatus, type WorkBuddyCandidateFailure, WorkBuddyCatalog, type WorkBuddyChatResult, type WorkBuddyCredential, type WorkBuddyCredentialRecovery, WorkBuddyCredentialRejectedError, WorkBuddyCredentialStore, type WorkBuddyCreditPackage, type WorkBuddyCredits, WorkBuddyEncryptedCredentialError, type WorkBuddyEncryptedField, type WorkBuddyHostHeartbeat, type WorkBuddyHostHeartbeatOwner, type WorkBuddyModelInfo, type WorkBuddyNativeModality, WorkBuddyPoolPreferences, type WorkBuddyProbeClient, type WorkBuddyProbeOutcome, type WorkBuddyProbeResult, type WorkBuddyProbeStore, type WorkBuddyReasoning, type WorkBuddyRecoveryCandidate, type WorkBuddyRefreshOutcome, WorkBuddyRegionState, type WorkBuddyShim, type WorkBuddyStatusRouteOptions, type WorkBuddyStoreOptions, WorkBuddyUpstreamClient, type WorkBuddyUpstreamModel, type WorkBuddyUsabilityProbeOptions, apply, asVolatile, authFileName, classifyUpstreamError, clearAtRestKeyCache, clearHostHeartbeat, cooldownOf, createAccountUsabilityProbe, createWorkBuddyAdapter, createWorkBuddyShim, creditOfStream, defaultDesktopAuthCandidates, defaultDesktopAuthDirs, defaultDesktopAuthPath, defaultOffModelIds, deriveAtRestKey, deriveAtRestKeyId, deriveCatalog, deriveStableConversationId, fallbackModelsFor, fetchAtRestKeyPayload, findWorkbuddyAppExecutable, hasEncryptedCredentialFields, imageDefaultFor, imageToolRegionOf, inject, isCredentialRejectedError, isEncryptedCredentialError, isEncryptedFieldWrapper, isHeartbeatProcessAlive, isWorkbuddyBundle, knownRegionOf, legacyAttributionRegion, legacyWorkbuddyOwnAuthPath, macosBundleExecutable, macosNestedAppBundles, modelIdOfBody, name, nativeModalityOf, nextRegionEnabled, nextRegionSlots, offDefaultFor, openEncryptedField, outcomeOfFailure, parseCreditMultiplier, parseReasoning, parseRetryAfter, parseUpstreamModel, parseWorkBuddyAuth, prepareChatBody, probeModel, probeRequestBody, probeSucceeded, processStartTimeMs, readAtRestKey, readHostHeartbeat, realTierAvailabilityFor, regionCleared, regionEnabled, regionEnabledOf, regionOf, regionOfProvider, regionOfStatusUrl, regionStateOf, regionsFieldIsCorrupt, regionsMapOf, registerWorkBuddyStatusRoute, resolveCredentialRecovery, selectAccountFor, settingsNamespaceOf, toPersistedWorkBuddyModel, unwrapVolatileDeep, videoToolRegionOf, withEffectiveOff, withWorkBuddyRegion, workBuddyDisplayName, workBuddyModelInput, workBuddyThinkingLevelMap, workBuddyWebStatus, workbuddyAccountId, workbuddyAppExecutableCandidates, workbuddyHostHeartbeatPath, workbuddyOwnAuthPath, writeHostHeartbeat };
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as CREDENTIAL_REJECTED_CODE, $t as isWatermarkFreeImageModel, A as withoutRouters, An as workbuddyAppExecutableCandidates, At as REFUSES_OFF_MODEL_IDS, B as defaultDesktopAuthPath, Bt as parseSupportedSecondsRange, C as setDeviceMode, Ct as regionOf, D as applyContextBudgets, Dn as macosNestedAppBundles, Dt as attachBusyLevels, E as WorkBuddyCatalog, En as macosBundleExecutable, Et as toolSchemaRejectAdvice, F as WorkBuddyCredentialStore, Ft as recordRefusal, G as parseWorkBuddyAuth, Gt as IMAGE_TAG_TEXT_TO_IMAGE, H as isEncryptedCredentialError, Ht as resolveVideoParams, I as WorkBuddyEncryptedCredentialError, It as withEffectiveOff, J as workbuddyOwnAuthPath, Jt as imageDataUrl, K as preferredAccountName, Kt as MAX_INPUT_IMAGE_BYTES, L as authFileName, Lt as VIDEO_TAG_IMAGE_TO_VIDEO, M as WORKBUDDY_AUTH_FILENAME, Mn as resolveDshHome, Mt as lastRefusalFor, N as WORKBUDDY_AUTH_FILE_ENV, Nn as withFileLock, Nt as offDefaultFor, O as deriveCatalog, On as openEncryptedField, Ot as promoBadgeTone, Pn as writeFileAtomic, Pt as offRefused, Q as CONTEXT_OVERFLOW_MARKER, Qt as isBareBase64Image, R as defaultDesktopAuthCandidates, Rt as VIDEO_TAG_TEXT_TO_VIDEO, S as saveDeviceSdkSettings, Sn as findWorkbuddyAppExecutable, St as prepareChatBody, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as isWorkbuddyBundle, Tt as rewriteSessionTitleModel, U as isVaultAccountId, Ut as IMAGE_SIZE_LIMITS_WIDE, V as hasEncryptedCredentialFields, Vt as pickVideoModel, W as legacyWorkbuddyOwnAuthPath, Wt as IMAGE_TAG_IMAGE_TO_IMAGE, X as APP_VERSION, Xt as imageModelChoices, Yt as imageMimeForPath, Z as BODY_OVERSIZE_MARKER, Zt as imageSizeLimitsOf, _ as createDeviceProfileLookup, _n as WORKBUDDY_APP_EXECUTABLE_ENV, _t as openingEvidenceOfBody, a as readHostHeartbeat, an as pruneTempDir, at as classifyUpstreamError, b as readDeviceSettings, bn as deriveAtRestKeyId, bt as parseUpstreamModel, c as WORKBUDDY_CONNECT_VERSION, cn as nativeModalityOf, ct as forceNeutralHead, dt as isConversationIdGateBody, en as parseImageDataUrl, ft as isCredentialRejectedError, g as createTuringSdk, gt as modelIdOfBody, h as createDeviceSdkPort, ht as knownRegionOf, i as processStartTimeMs, in as queueNoticeText, it as channelGateMemberOf, j as ENCRYPTED_CREDENTIAL_CODE, jt as defaultOffModelIds, k as fallbackModelsFor, kn as readAtRestKey, kt as selectPromoBadge, l as createFileRosterSeenStore, lt as isBodyOversizeRefusal, m as piAiRuntimeInfo, mn as isDeviceId, mt as isToolSchemaRejectBody, n as clearHostHeartbeat, nn as sniffImageMime, nt as WorkBuddyCredentialRejectedError, o as workbuddyHostHeartbeatPath, on as NATIVE_MODALITY_BY_MODEL_ID, ot as declaredTools, p as resolveCnGateway, pt as isFirstMessageGateBody, q as workbuddyAccountId, qt as WorkBuddyImageError, r as isHeartbeatProcessAlive, rn as parseQueueAnswer, rt as WorkBuddyUpstreamClient, s as writeHostHeartbeat, sn as imageDefaultFor, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tn as pickMediaModel, tt as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, ut as isContextTooLongBody, v as describeDerivedDevices, vn as clearAtRestKeyCache, vt as parseCreditMultiplier, w as FALLBACK_WORKBUDDY_MODELS, wn as isEncryptedFieldWrapper, wt as requestEvidenceOf, x as saveDeviceProfile, xn as fetchAtRestKeyPayload, xt as perturbChannelFingerprints, y as isDeviceMode, yn as deriveAtRestKey, yt as parseReasoning, z as defaultDesktopAuthDirs, zt as WorkBuddyVideoError } from "./host-heartbeat-1ytBqhSr.js";
1
+ import { $ as CREDENTIAL_REJECTED_CODE, $t as isBareBase64Image, A as withoutRouters, An as readAtRestKey, At as selectPromoBadge, B as defaultDesktopAuthPath, Bt as WorkBuddyVideoError, C as setDeviceMode, Cn as findWorkbuddyAppExecutable, Ct as prepareChatBody, D as applyContextBudgets, Dn as macosBundleExecutable, Dt as toolSchemaRejectAdvice, E as WorkBuddyCatalog, En as isWorkbuddyBundle, Et as rewriteSessionTitleModel, F as WorkBuddyCredentialStore, Fn as writeFileAtomic, Ft as offRefused, G as parseWorkBuddyAuth, Gt as IMAGE_TAG_IMAGE_TO_IMAGE, H as isEncryptedCredentialError, Ht as pickVideoModel, I as WorkBuddyEncryptedCredentialError, It as recordRefusal, J as workbuddyOwnAuthPath, Jt as WorkBuddyImageError, K as preferredAccountName, Kt as IMAGE_TAG_TEXT_TO_IMAGE, L as authFileName, Lt as withEffectiveOff, M as WORKBUDDY_AUTH_FILENAME, Mt as defaultOffModelIds, N as WORKBUDDY_AUTH_FILE_ENV, Nn as resolveDshHome, Nt as lastRefusalFor, O as deriveCatalog, On as macosNestedAppBundles, Ot as attachBusyLevels, Pn as withFileLock, Pt as offDefaultFor, Q as CONTEXT_OVERFLOW_MARKER, Qt as imageSizeLimitsOf, R as defaultDesktopAuthCandidates, Rt as VIDEO_TAG_IMAGE_TO_VIDEO, S as saveDeviceSdkSettings, Sn as fetchAtRestKeyPayload, St as perturbChannelFingerprints, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as isEncryptedFieldWrapper, Tt as requestEvidenceOf, U as isVaultAccountId, Ut as resolveVideoParams, V as hasEncryptedCredentialFields, Vt as parseSupportedSecondsRange, W as legacyWorkbuddyOwnAuthPath, Wt as IMAGE_SIZE_LIMITS_WIDE, X as APP_VERSION, Xt as imageMimeForPath, Yt as imageDataUrl, Z as BODY_OVERSIZE_MARKER, Zt as imageModelChoices, _ as createDeviceProfileLookup, _t as modelIdOfBody, a as readHostHeartbeat, an as queueNoticeText, at as classifyUpstreamError, b as readDeviceSettings, bn as deriveAtRestKey, bt as parseReasoning, c as WORKBUDDY_CONNECT_VERSION, cn as imageDefaultFor, dt as isContextTooLongBody, en as isWatermarkFreeImageModel, ft as isConversationIdGateBody, g as createTuringSdk, gt as knownRegionOf, h as createDeviceSdkPort, hn as isDeviceId, ht as isToolSchemaRejectBody, i as processStartTimeMs, in as parseQueueAnswer, it as channelGateMemberOf, j as ENCRYPTED_CREDENTIAL_CODE, jn as workbuddyAppExecutableCandidates, jt as REFUSES_OFF_MODEL_IDS, k as fallbackModelsFor, kn as openEncryptedField, kt as promoBadgeTone, l as createFileRosterSeenStore, ln as nativeModalityOf, lt as forceNeutralHead, m as piAiRuntimeInfo, mt as isFirstMessageGateBody, n as clearHostHeartbeat, nn as pickMediaModel, nt as WorkBuddyCredentialRejectedError, o as workbuddyHostHeartbeatPath, on as pruneTempDir, ot as declaredTools, p as resolveCnGateway, pt as isCredentialRejectedError, q as workbuddyAccountId, qt as MAX_INPUT_IMAGE_BYTES, r as isHeartbeatProcessAlive, rn as sniffImageMime, rt as WorkBuddyUpstreamClient, s as writeHostHeartbeat, sn as NATIVE_MODALITY_BY_MODEL_ID, st as deriveStableConversationId, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tn as parseImageDataUrl, tt as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, ut as isBodyOversizeRefusal, v as describeDerivedDevices, vn as WORKBUDDY_APP_EXECUTABLE_ENV, vt as openingEvidenceOfBody, w as FALLBACK_WORKBUDDY_MODELS, wt as regionOf, x as saveDeviceProfile, xn as deriveAtRestKeyId, xt as parseUpstreamModel, y as isDeviceMode, yn as clearAtRestKeyCache, yt as parseCreditMultiplier, z as defaultDesktopAuthDirs, zt as VIDEO_TAG_TEXT_TO_VIDEO } from "./host-heartbeat-BUtle_vT.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { appendFile, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -3523,12 +3523,39 @@ function attachUsage(directory, report, onError) {
3523
3523
  * the minimum for these surfaces, not a substitute for a secret when a route
3524
3524
  * spends credit.
3525
3525
  *
3526
+ * ## The deployment-declared authority (issue #261)
3527
+ *
3528
+ * Behind a reverse proxy both questions break for a reason the two callers
3529
+ * cannot see: the harness's webserver is bound to a loopback address, so the
3530
+ * socket ALWAYS lands on 127.0.0.1, while the browser (and the proxy forwarding
3531
+ * its Host unchanged) addresses the public authority — e.g. `192.168.1.250`.
3532
+ * `isLocalHostname` says no, and the Host-vs-`localAddress` comparison can never
3533
+ * equal, so EVERY card route answers 403 `host-not-trusted` even though the
3534
+ * harness's own `/api` fence accepts exactly that Host (it has a `trustedHosts`
3535
+ * allow-list, `dsh web --trusted-host 192.168.1.250`).
3536
+ *
3537
+ * The fix is a third, opt-in source of "this machine": a list of authorities the
3538
+ * DEPLOYER declared trusted, threaded into both predicates as one
3539
+ * {@link TrustedHosts} value so Host and Origin cannot disagree. This does not
3540
+ * weaken rebinding defense: an attacker page's Host is its own domain, which is
3541
+ * not on the list; loopback and the listener's own address are still accepted
3542
+ * before it, and `0.0.0.0` / `[::]` are still refused. It only aligns the
3543
+ * plugin's notion of "ours" with the harness's for the same request.
3544
+ *
3545
+ * We deliberately do NOT read the harness's own `trustedHosts` off the
3546
+ * `connection` service: in the DSH line this plugin runs against that field is
3547
+ * private on `HostConnectionService`, and depending on another service being
3548
+ * mounted would make the card disappear when it is absent. Keeping the allow-list
3549
+ * in this plugin's own Config is self-contained and version-independent; see
3550
+ * `docs/ISSUE-261-REPLY.md`.
3551
+ *
3526
3552
  * ## Two callers, two strictnesses (deliberate)
3527
3553
  *
3528
3554
  * - `src/web-status.ts` serves the settings card over the HOST's webserver, which
3529
3555
  * the harness may configure to bind a concrete non-loopback address. It uses
3530
- * `hostMatchesListener` / `originIsLoopback(origin, localAddress)`, i.e. "is
3531
- * this addressed to / coming from the interface the connection landed on".
3556
+ * `hostMatchesListener` / `originIsLoopback(origin, localAddress, trustedHosts)`,
3557
+ * i.e. "is this addressed to / coming from the interface the connection landed
3558
+ * on, OR from an authority the deployer explicitly declared trusted".
3532
3559
  * - `src/shim.ts` binds `listen(0, '127.0.0.1')` itself, so no LAN request can
3533
3560
  * ever reach it. It uses the stricter `hostIsLoopback`, which is not a
3534
3561
  * different notion of "local" but the same one narrowed to the only case that
@@ -3602,6 +3629,80 @@ function hostnameOfHost(host) {
3602
3629
  return hostname;
3603
3630
  }
3604
3631
  /**
3632
+ * Reduce a bare `host[:port]` authority to its WHATWG-normalized parts.
3633
+ *
3634
+ * `new URL` is the authority on spelling, for the same reason the harness's own
3635
+ * `/api` fence uses it: it lowercases the host, brackets IPv6, strips a
3636
+ * scheme-default port and rejects shapes a browser would never put in Host.
3637
+ * The scheme matters because WHATWG strips DIFFERENT default ports for http:
3638
+ * (80) and https: (443): the Origin path parses each entry under the Origin's
3639
+ * OWN scheme, exactly as the harness's `isSameAuthorityOrigin` re-parses the
3640
+ * Host under the Origin's scheme. Without that, an entry `host:443` would match
3641
+ * the Host half (`http://host:443` keeps `:443`) but never an https Origin
3642
+ * (`https://host:443` drops it) — a split in the wrong direction, and the very
3643
+ * thing this module exists to prevent.
3644
+ *
3645
+ * Returns `undefined` for anything with a path, userinfo, whitespace or a
3646
+ * dangling colon — a configured entry like `harness.internal/path` or one
3647
+ * carrying embedded credentials before the hostname must never grant the
3648
+ * hostname buried inside it.
3649
+ */
3650
+ function authorityParts(authority, scheme = "http:") {
3651
+ try {
3652
+ const url = new URL(`${scheme}//${authority}`);
3653
+ if (url.pathname !== "/" || url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return void 0;
3654
+ return {
3655
+ hostname: url.hostname,
3656
+ host: url.host
3657
+ };
3658
+ } catch {
3659
+ return;
3660
+ }
3661
+ }
3662
+ /**
3663
+ * Fail loudly on a `trustedHosts` entry that is not a canonical bare authority.
3664
+ *
3665
+ * A typo (`host/path`, embedded credentials, `host :80`, `0x7f.0.0.1`,
3666
+ * percent-encoding)
3667
+ * must fail the LOAD, not sit in the list silently authorizing a hostname prefix
3668
+ * — the harness's own `assertTrustedAuthority` has the same boundary. Canonical
3669
+ * means WHATWG parsing did not rewrite it (case / default-port aside), so an
3670
+ * entry never grants a different authority than the operator wrote.
3671
+ */
3672
+ function assertTrustedAuthority(entry) {
3673
+ const parsed = authorityParts(entry);
3674
+ if (parsed === void 0 || parsed.host.toLowerCase() !== entry.toLowerCase()) throw new Error(`dsh-connect-workbuddy: trustedHosts entry ${JSON.stringify(entry)} is not a bare host[:port] authority`);
3675
+ }
3676
+ /**
3677
+ * Whether a normalized authority is one of the deployer-declared ones.
3678
+ *
3679
+ * Comparison is on the WHOLE authority (host + explicit port), not on the bare
3680
+ * hostname. That distinction is the whole reason this helper exists: a request
3681
+ * behind a proxy carries BOTH `Host: 192.168.1.250:8443` and
3682
+ * `Origin: https://192.168.1.250:8443`, while `hostnameOfHost` and `URL.hostname`
3683
+ * have already stripped the port for the loopback / listener checks. Comparing a
3684
+ * `host:port` entry against those bare hostnames would never match, so the
3685
+ * Origin half would stay 403 after the Host half was fixed — the exact split
3686
+ * this module exists to prevent.
3687
+ *
3688
+ * An entry with an explicit port matches that exact authority; a port-less entry
3689
+ * (its `host` equals its `hostname`) matches the hostname on any port. Both
3690
+ * sides went through `authorityParts` under the SAME scheme, so case, a
3691
+ * redundant scheme-default port and IPv6 brackets never decide trust.
3692
+ */
3693
+ function matchesTrustedAuthority(parts, trustedHosts, scheme = "http:") {
3694
+ return trustedHosts.some((entry) => {
3695
+ const configured = authorityParts(entry, scheme);
3696
+ if (configured === void 0) return false;
3697
+ if (configured.host === configured.hostname) return configured.hostname === parts.hostname;
3698
+ return configured.host === parts.host;
3699
+ });
3700
+ }
3701
+ /** Read the trust list once per decision; an absent getter means "no grants". */
3702
+ function trustedList(getter) {
3703
+ return getter === void 0 ? [] : getter();
3704
+ }
3705
+ /**
3605
3706
  * Whether a Host header names the loopback interface.
3606
3707
  *
3607
3708
  * An absent Host is treated as NOT loopback. HTTP/1.1 requires the header, so
@@ -3649,12 +3750,23 @@ function isLocalHostname(hostname) {
3649
3750
  * `Host: 127.0.0.1` anyway. It is stated first so the answer does not depend on
3650
3751
  * how the platform spells its own loopback, and so an undefined `localAddress`
3651
3752
  * (a proxy, a test double) still admits genuine local traffic.
3753
+ *
3754
+ * BEHIND A REVERSE PROXY the comparison cannot succeed: the harness binds a
3755
+ * loopback address, so `localAddress` is always `127.0.0.1` while the browser
3756
+ * addresses the public authority. That is what `trustedHosts` is for (issue
3757
+ * #261) — a deployer-declared authority is checked BEFORE the `localAddress`
3758
+ * comparison, so a proxied request is admitted without touching the rebinding
3759
+ * defense (loopback and wildcard refusal are still first, and an attacker's
3760
+ * domain is by construction not on the list). An absent trust set leaves the
3761
+ * pre-#261 answer for every request.
3652
3762
  */
3653
- function hostMatchesListener(host, localAddress) {
3763
+ function hostMatchesListener(host, localAddress, trustedHosts) {
3654
3764
  if (host === void 0 || host.trim() === "") return false;
3655
3765
  const hostname = hostnameOfHost(host);
3656
3766
  if (isLocalHostname(hostname)) return true;
3657
3767
  if (hostname === "0.0.0.0" || hostname === "[::]") return false;
3768
+ const parts = authorityParts(host.trim());
3769
+ if (parts !== void 0 && matchesTrustedAuthority(parts, trustedList(trustedHosts))) return true;
3658
3770
  if (localAddress === void 0 || localAddress.trim() === "") return false;
3659
3771
  const local = localAddress.trim().toLowerCase();
3660
3772
  if (!isIpLiteral(local) && !isIpLiteral(`[${local}]`)) return false;
@@ -3684,13 +3796,28 @@ function hostMatchesListener(host, localAddress) {
3684
3796
  * running on this machine), and treating it as one would break legitimate
3685
3797
  * setups behind a proxy that terminates on a different port than it forwards to.
3686
3798
  * That intentional limit is recorded rather than silently assumed.
3687
- */
3688
- function originIsLoopback(origin, localAddress) {
3799
+ *
3800
+ * A DEPLOYER-DECLARED authority (issue #261) is different: a proxied browser
3801
+ * sends `Origin: https://192.168.1.250:8443` while the socket lands on
3802
+ * 127.0.0.1, so neither the loopback branch nor the `localAddress` comparison
3803
+ * can ever admit it. It is checked on the Origin's WHOLE authority (`host`,
3804
+ * port included) via the SAME `matchesTrustedAuthority` the Host path uses —
3805
+ * that is what keeps the two halves from diverging again. Both halves parse the
3806
+ * entries under the Origin's scheme (see `authorityParts`), so an entry with an
3807
+ * explicit scheme-default port (`:443`) still matches an https Origin whose URL
3808
+ * dropped that port, and a port-less entry matches on any port. Only http(s)
3809
+ * Origins can name this listener; every other scheme fails the check below.
3810
+ */
3811
+ function originIsLoopback(origin, localAddress, trustedHosts) {
3689
3812
  if (origin === void 0 || origin.trim() === "") return true;
3690
3813
  try {
3691
- const { hostname } = new URL(origin);
3814
+ const { protocol, hostname, host } = new URL(origin);
3815
+ const scheme = protocol === "https:" ? "https:" : protocol === "http:" ? "http:" : void 0;
3816
+ if (scheme === void 0) return false;
3692
3817
  if (isLocalHostname(hostname)) return true;
3693
- return hostMatchesListener(hostname, localAddress);
3818
+ const parts = authorityParts(host, scheme);
3819
+ if (parts !== void 0 && matchesTrustedAuthority(parts, trustedList(trustedHosts), scheme)) return true;
3820
+ return hostMatchesListener(hostname, localAddress, trustedHosts);
3694
3821
  } catch {
3695
3822
  return false;
3696
3823
  }
@@ -11876,13 +12003,21 @@ function readJsonBody(req, limitBytes = PROBE_BODY_LIMIT) {
11876
12003
  * Absent Host is refused: HTTP/1.1 requires it, and its absence on a
11877
12004
  * credit-spending surface is not worth the benefit of the doubt. Absent Origin
11878
12005
  * passes, because that is the shape of the plugin's own fetch and of curl.
12006
+ *
12007
+ * `trustedHosts` (issue #261) is a THIRD, opt-in input, and it changes none of
12008
+ * the above: it is still a forgeable header decision, not authentication. It only
12009
+ * admits a Host/Origin authority the deployer declared, which is what a reverse
12010
+ * proxy needs (the harness binds loopback, so `localAddress` is always 127.0.0.1
12011
+ * and the browser's public authority could never match it). The same getter is
12012
+ * passed to BOTH halves so a request cannot be half-trusted. See `loopback.ts`.
11879
12013
  */
11880
- function requireLoopback(req, res) {
11881
- if (!hostMatchesListener(req.headers.host, req.socket?.localAddress)) {
12014
+ function requireLoopback(req, res, deps) {
12015
+ const trustedHosts = deps.trustedHosts;
12016
+ if (!hostMatchesListener(req.headers.host, req.socket?.localAddress, trustedHosts)) {
11882
12017
  json(res, 403, { error: "host-not-trusted" });
11883
12018
  return false;
11884
12019
  }
11885
- if (!originIsLoopback(req.headers.origin, req.socket?.localAddress)) {
12020
+ if (!originIsLoopback(req.headers.origin, req.socket?.localAddress, trustedHosts)) {
11886
12021
  json(res, 403, { error: "origin-not-trusted" });
11887
12022
  return false;
11888
12023
  }
@@ -12387,7 +12522,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12387
12522
  path: spec.path,
12388
12523
  handler: async (req, res) => {
12389
12524
  if (req.method !== spec.method) return json(res, 405, { error: "method not allowed" });
12390
- if (!requireLoopback(req, res)) return;
12525
+ if (!requireLoopback(req, res, deps)) return;
12391
12526
  if (spec.ready !== void 0 && !spec.ready(res)) return;
12392
12527
  try {
12393
12528
  await run(req, res);
@@ -12532,7 +12667,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12532
12667
  path: WORKBUDDY_POOL_PATH,
12533
12668
  handler: async (req, res) => {
12534
12669
  if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12535
- if (!requireLoopback(req, res)) return;
12670
+ if (!requireLoopback(req, res, deps)) return;
12536
12671
  const region = requestRegion(req, res);
12537
12672
  if (region === void 0) return;
12538
12673
  const action = poolActionOf(req.url ?? "/");
@@ -12675,7 +12810,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12675
12810
  path: "/plugins/dsh-connect-workbuddy/__save",
12676
12811
  handler: async (req, res) => {
12677
12812
  if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12678
- if (!requireLoopback(req, res)) return;
12813
+ if (!requireLoopback(req, res, deps)) return;
12679
12814
  const settings = ctx.get?.("settings");
12680
12815
  if (settings === void 0) return json(res, 503, { error: "settings service unavailable to this fiber" });
12681
12816
  try {
@@ -12781,7 +12916,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12781
12916
  path: WORKBUDDY_TRANSFER_PATH,
12782
12917
  handler: async (req, res) => {
12783
12918
  if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12784
- if (!requireLoopback(req, res)) return;
12919
+ if (!requireLoopback(req, res, deps)) return;
12785
12920
  const region = requestRegion(req, res);
12786
12921
  if (region === void 0) return;
12787
12922
  const action = transferActionOf(req.url ?? "/");
@@ -12851,7 +12986,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12851
12986
  kind: "exact",
12852
12987
  path: WORKBUDDY_DEVICE_PROFILE_PATH,
12853
12988
  handler: async (req, res) => {
12854
- if (!requireLoopback(req, res)) return;
12989
+ if (!requireLoopback(req, res, deps)) return;
12855
12990
  const port = deps.deviceSettings;
12856
12991
  if (port === void 0) return json(res, 503, {
12857
12992
  reason: "device-settings-unavailable",
@@ -12950,7 +13085,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12950
13085
  kind: "exact",
12951
13086
  path: WORKBUDDY_DEVICE_SDK_PATH,
12952
13087
  handler: async (req, res) => {
12953
- if (!requireLoopback(req, res)) return;
13088
+ if (!requireLoopback(req, res, deps)) return;
12954
13089
  const port = deps.deviceSdk;
12955
13090
  if (port === void 0) return json(res, 503, {
12956
13091
  reason: "device-sdk-unavailable",
@@ -13338,6 +13473,7 @@ const Config = z.object({
13338
13473
  z.const("always")
13339
13474
  ]).default("failure").description("When to perturb scanned messages with invisible characters: \"off\" only rescues after a channel-gate refusal, \"failure\" (default) learns from a successful rescue and starts later requests perturbed, \"always\" starts every request with the dense rescue for a gateway whose plain attempt is guaranteed to fail.")),
13340
13475
  usageIdentity: asVolatile(z.boolean().default(false).description("Send the chat conversation ids in the official client's 32-hex UUIDv7 shape and add a mirroring X-Request-ID. Off by default — it is a display alignment measured by a reporter, not by this plugin, and the chat channel identity (User-Agent) and request body never change.")),
13476
+ stableConversationId: asVolatile(z.boolean().default(false).description("A/B 开关(路线 A,默认关):开启时把 X-Conversation-ID 固定为从请求体不变前缀派生的亲和键(其余三件套仍每请求现生成)。该值不是宿主会话标识,不宣称会话隔离,也不证明上游按会话分区;相同前缀的独立会话会共享键。关闭时不进入派生分支。用于离线单变量命中率对照,详见 docs/STABLE-KEY-SEMANTICS.md。改动后需重载插件(配置在挂载时采样一次)。")),
13341
13477
  wireProfile: asVolatile(z.union([z.const("conservative"), z.const("balanced")]).default("balanced").description("Outbound identity profile. \"balanced\" (default) makes every request claim the same client (WorkBuddy product/IDE/agent headers, X-CodeBuddy-Request, Accept-Language, X-Root-Request-ID, and a per-account X-Machine-ID/X-Session-ID pair) and gives the billing routes a User-Agent plus Origin/Referer. \"conservative\" restores the 5.16.0 bytes exactly, including X-Product: SaaS.")),
13342
13478
  /**
13343
13479
  * How often the card re-reads the usage document.
@@ -13376,6 +13512,29 @@ const Config = z.object({
13376
13512
  extraInjectedPrefixes: asVolatile(z.array(z.string()).default([]).description("Extra literal prefixes (issue #133) treated like the harness-injected context markers when keepPromptLast is on — for blocks a companion plugin injects that the built-in list does not recognize. Each entry matches the start of a trailing user message; read only while keepPromptLast is enabled. Sampled when the plugin mounts: reload the plugin (or restart the host) after changing it.")),
13377
13513
  dropForeignThinking: asVolatile(z.boolean().default(false).description("Drop foreign thinking blocks that pi-ai would publish as prose (issue #147). CROSS-PROVIDER turns are dropped automatically: after a provider switch the other provider's unsigned thinking blocks can never be replayed, and pi-ai would flatten them into assistant prose that the gateway refuses with 11128 (issue #163's measured scene). This switch only widens the repair to a model switch inside one of this bundle's own routes. On, those blocks are removed from the request; text and tool calls are untouched. Off by default for the same-route leg because it changes bytes the upstream counts.")),
13378
13514
  dropAllThinking: asVolatile(z.boolean().default(false).description("Strip EVERY historical thinking block before the request goes out (issue #213). The channel gate scans the request text, and a 11128 report matched every banned opening against this session's own reasoning blocks: WorkBuddy answers reasoning in `reasoning_content`, pi-ai records that field name as the block signature and replays it under the same name, so past reasoning rides along in the request and is one of the things carrying the text the gate refuses. On, all thinking blocks are removed from the request; your messages, tool calls and the model's answers are untouched, but the model no longer sees its own earlier reasoning. OFF by default: that loss is real, so it is a deliberate answer to a 11128 you can match to reasoning text, not a default. Takes effect on the next turn, no reload.")),
13515
+ /**
13516
+ * Authorities the deployer declared trusted for the plugin's own routes
13517
+ * (issue #261). OFF (empty) by default, so nothing changes for a loopback or
13518
+ * LAN-bound deployment. Add the public authority when DSH sits behind a
13519
+ * reverse proxy that forwards Host unchanged: the harness binds a loopback
13520
+ * address, so `req.socket.localAddress` is always 127.0.0.1 and the card's
13521
+ * Host/Origin gate can never match `Host: <public authority>` — every route
13522
+ * would answer 403 `host-not-trusted` even though the harness's own `/api`
13523
+ * accepts that same Host via `--trusted-host`.
13524
+ *
13525
+ * Each entry is a bare `host[:port]` authority; a port-less entry matches the
13526
+ * hostname on any port, an explicit-port entry matches exactly that
13527
+ * authority. Values are validated by `assertTrustedAuthority` at mount so a
13528
+ * typo fails loudly instead of silently granting a hostname prefix. This is
13529
+ * NOT authentication (Host/Origin are forgeable) and does not weaken DNS
13530
+ * rebinding defense: an attacker's domain is not on the list, loopback and
13531
+ * the listener's own address are still accepted first, and `0.0.0.0`/`[::]`
13532
+ * are still refused.
13533
+ *
13534
+ * Volatile and read at REQUEST time: adding an authority must not require a
13535
+ * full plugin reload (which would drop in-flight requests) to take effect.
13536
+ */
13537
+ trustedHosts: asVolatile(z.array(z.string()).default([]).description("Extra Host authorities the plugin's settings-card routes accept when DSH sits behind a reverse proxy (e.g. [\"192.168.1.250:8443\"] or [\"dsh.example.com\"]). Each entry is a bare host[:port]; a port-less entry matches that host on any port. Loopback, the listener's own address and the 0.0.0.0/[::] refusal are unchanged. Off by default. Takes effect without a reload.")),
13379
13538
  sessionTitle: asVolatile(z.object({
13380
13539
  enabled: z.boolean().default(false),
13381
13540
  model: z.string().default("wb-lite")
@@ -13556,6 +13715,19 @@ async function legacyAttributionRegion(value, accountsFor) {
13556
13715
  * upstream never leaves a provider empty.
13557
13716
  */
13558
13717
  function apply(ctx, config) {
13718
+ /**
13719
+ * 反代部署下插件自己路由的可信 Host(issue #261)。
13720
+ *
13721
+ * 在挂载期逐条校验「裸 authority」,拼错的值宁可让插件加载失败,也不要等请求
13722
+ * 时才 403、或悄悄授权一个 hostname 前缀(宿主自己的 `assertTrustedAuthority`
13723
+ * 是同一条边界)。但**读取**放在下面的 `trustedHosts()` 里、每次请求现读:
13724
+ * 这是个 volatile 字段,用户加一条白名单不该触发整插件重载(会丢在途请求)。
13725
+ */
13726
+ const trustedHosts = () => {
13727
+ const value = unwrapVolatile(config.trustedHosts) ?? [];
13728
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
13729
+ };
13730
+ for (const entry of trustedHosts()) assertTrustedAuthority(entry);
13559
13731
  /**
13560
13732
  * 每账号的设备覆盖值(设置里齿轮改的那份)。
13561
13733
  *
@@ -13629,6 +13801,7 @@ function apply(ctx, config) {
13629
13801
  ctx.logger.warn(`dsh-connect-workbuddy: ${message}`);
13630
13802
  }, {
13631
13803
  usageIdentity: unwrapVolatile(config.usageIdentity) === true,
13804
+ stableConversationId: unwrapVolatile(config.stableConversationId) === true,
13632
13805
  ...unwrapVolatile(config.wireProfile) === void 0 ? {} : { profile: unwrapVolatile(config.wireProfile) }
13633
13806
  }, (() => {
13634
13807
  const token = unwrapVolatile(config.deviceToken);
@@ -14403,6 +14576,7 @@ function apply(ctx, config) {
14403
14576
  return registerWorkBuddyStatusRoute(webCtx, {
14404
14577
  store: (region) => stacks[region].store,
14405
14578
  client,
14579
+ trustedHosts,
14406
14580
  accountUsable: accountUsabilityProbe,
14407
14581
  /**
14408
14582
  * The CLI route's live turns, for the composer readout.
@@ -15857,4 +16031,4 @@ function apply(ctx, config) {
15857
16031
  });
15858
16032
  }
15859
16033
  //#endregion
15860
- export { CREDENTIAL_REJECTED_CODE, Config, DEFAULT_PROBE_INPUT_TOKENS, ENCRYPTED_CREDENTIAL_CODE, FALLBACK_WORKBUDDY_MODELS, FALLBACK_WORKBUDDY_MODELS_GLOBAL, NATIVE_MODALITY_BY_MODEL_ID, PROBE_INPUT_TOKEN_CHOICES, PROBE_MAX_TOKENS, PROBE_SYSTEM_PROMPT, REFUSES_OFF_MODEL_IDS, WORKBUDDY_ACCOUNTS_REFRESH_PATH, WORKBUDDY_APP_EXECUTABLE_ENV, WORKBUDDY_AUTH_FILENAME, WORKBUDDY_AUTH_FILE_ENV, WORKBUDDY_CHECKIN_PATH, WORKBUDDY_CONNECT_VERSION, WORKBUDDY_GLOBAL_PROVIDER, WORKBUDDY_HOST_HEARTBEAT_FILENAME, WORKBUDDY_MODELS_REFRESH_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_PROVIDER, WORKBUDDY_PROVIDERS, WORKBUDDY_PROVIDER_DISPLAY_NAMES, WORKBUDDY_REGIONS, WORKBUDDY_REGION_PARAM, WORKBUDDY_SETTINGS_NS, WORKBUDDY_STREAM_IDLE_TIMEOUT_MS, WORKBUDDY_TPS_PATH, WORKBUDDY_USAGE_PATH, WorkBuddyCatalog, WorkBuddyCredentialRejectedError, WorkBuddyCredentialStore, WorkBuddyEncryptedCredentialError, WorkBuddyUpstreamClient, apply, asVolatile, authFileName, classifyUpstreamError, clearAtRestKeyCache, clearHostHeartbeat, cooldownOf, createAccountUsabilityProbe, createWorkBuddyAdapter, createWorkBuddyShim, creditOfStream, defaultDesktopAuthCandidates, defaultDesktopAuthDirs, defaultDesktopAuthPath, defaultOffModelIds, deriveAtRestKey, deriveAtRestKeyId, deriveCatalog, fallbackModelsFor, fetchAtRestKeyPayload, findWorkbuddyAppExecutable, hasEncryptedCredentialFields, imageDefaultFor, imageToolRegionOf, inject, isCredentialRejectedError, isEncryptedCredentialError, isEncryptedFieldWrapper, isHeartbeatProcessAlive, isWorkbuddyBundle, knownRegionOf, legacyAttributionRegion, legacyWorkbuddyOwnAuthPath, macosBundleExecutable, macosNestedAppBundles, modelIdOfBody, name, nativeModalityOf, nextRegionEnabled, nextRegionSlots, offDefaultFor, openEncryptedField, outcomeOfFailure, parseCreditMultiplier, parseReasoning, parseRetryAfter, parseUpstreamModel, parseWorkBuddyAuth, prepareChatBody, probeModel, probeRequestBody, probeSucceeded, processStartTimeMs, readAtRestKey, readHostHeartbeat, realTierAvailabilityFor, regionCleared, regionEnabled, regionEnabledOf, regionOf, regionOfProvider, regionOfStatusUrl, regionStateOf, regionsFieldIsCorrupt, regionsMapOf, registerWorkBuddyStatusRoute, resolveCredentialRecovery, selectAccountFor, settingsNamespaceOf, toPersistedWorkBuddyModel, unwrapVolatileDeep, videoToolRegionOf, withEffectiveOff, withWorkBuddyRegion, workBuddyDisplayName, workBuddyModelInput, workBuddyThinkingLevelMap, workBuddyWebStatus, workbuddyAccountId, workbuddyAppExecutableCandidates, workbuddyHostHeartbeatPath, workbuddyOwnAuthPath, writeHostHeartbeat };
16034
+ export { CREDENTIAL_REJECTED_CODE, Config, DEFAULT_PROBE_INPUT_TOKENS, ENCRYPTED_CREDENTIAL_CODE, FALLBACK_WORKBUDDY_MODELS, FALLBACK_WORKBUDDY_MODELS_GLOBAL, NATIVE_MODALITY_BY_MODEL_ID, PROBE_INPUT_TOKEN_CHOICES, PROBE_MAX_TOKENS, PROBE_SYSTEM_PROMPT, REFUSES_OFF_MODEL_IDS, WORKBUDDY_ACCOUNTS_REFRESH_PATH, WORKBUDDY_APP_EXECUTABLE_ENV, WORKBUDDY_AUTH_FILENAME, WORKBUDDY_AUTH_FILE_ENV, WORKBUDDY_CHECKIN_PATH, WORKBUDDY_CONNECT_VERSION, WORKBUDDY_GLOBAL_PROVIDER, WORKBUDDY_HOST_HEARTBEAT_FILENAME, WORKBUDDY_MODELS_REFRESH_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_PROVIDER, WORKBUDDY_PROVIDERS, WORKBUDDY_PROVIDER_DISPLAY_NAMES, WORKBUDDY_REGIONS, WORKBUDDY_REGION_PARAM, WORKBUDDY_SETTINGS_NS, WORKBUDDY_STREAM_IDLE_TIMEOUT_MS, WORKBUDDY_TPS_PATH, WORKBUDDY_USAGE_PATH, WorkBuddyCatalog, WorkBuddyCredentialRejectedError, WorkBuddyCredentialStore, WorkBuddyEncryptedCredentialError, WorkBuddyUpstreamClient, apply, asVolatile, authFileName, classifyUpstreamError, clearAtRestKeyCache, clearHostHeartbeat, cooldownOf, createAccountUsabilityProbe, createWorkBuddyAdapter, createWorkBuddyShim, creditOfStream, defaultDesktopAuthCandidates, defaultDesktopAuthDirs, defaultDesktopAuthPath, defaultOffModelIds, deriveAtRestKey, deriveAtRestKeyId, deriveCatalog, deriveStableConversationId, fallbackModelsFor, fetchAtRestKeyPayload, findWorkbuddyAppExecutable, hasEncryptedCredentialFields, imageDefaultFor, imageToolRegionOf, inject, isCredentialRejectedError, isEncryptedCredentialError, isEncryptedFieldWrapper, isHeartbeatProcessAlive, isWorkbuddyBundle, knownRegionOf, legacyAttributionRegion, legacyWorkbuddyOwnAuthPath, macosBundleExecutable, macosNestedAppBundles, modelIdOfBody, name, nativeModalityOf, nextRegionEnabled, nextRegionSlots, offDefaultFor, openEncryptedField, outcomeOfFailure, parseCreditMultiplier, parseReasoning, parseRetryAfter, parseUpstreamModel, parseWorkBuddyAuth, prepareChatBody, probeModel, probeRequestBody, probeSucceeded, processStartTimeMs, readAtRestKey, readHostHeartbeat, realTierAvailabilityFor, regionCleared, regionEnabled, regionEnabledOf, regionOf, regionOfProvider, regionOfStatusUrl, regionStateOf, regionsFieldIsCorrupt, regionsMapOf, registerWorkBuddyStatusRoute, resolveCredentialRecovery, selectAccountFor, settingsNamespaceOf, toPersistedWorkBuddyModel, unwrapVolatileDeep, videoToolRegionOf, withEffectiveOff, withWorkBuddyRegion, workBuddyDisplayName, workBuddyModelInput, workBuddyThinkingLevelMap, workBuddyWebStatus, workbuddyAccountId, workbuddyAppExecutableCandidates, workbuddyHostHeartbeatPath, workbuddyOwnAuthPath, writeHostHeartbeat };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-connect-workbuddy",
3
3
  "displayName": "DSH Connect WorkBuddy",
4
4
  "description": "把本机登录的 WorkBuddy 模型(国内版与国际版)接入 DeepSeek Harness:每次刷新按上游目录自动读取每个模型的积分倍率,支持逐模型图片输入开关、多账号切换与账号池自动换号,并提供每日签到、卡片与输入框里的胶囊积分读数等只读积分概览。",
5
- "version": "5.24.6",
5
+ "version": "5.24.8",
6
6
  "author": "dingminhua",
7
7
  "copyright": "Copyright (c) 2026 LaoDing",
8
8
  "license": "MIT",
@@ -44,6 +44,7 @@
44
44
  "locale",
45
45
  "docs/assets",
46
46
  "docs/PRIVACY.md",
47
+ "docs/STABLE-KEY-SEMANTICS.md",
47
48
  "screenshots.json",
48
49
  "cordis.patch.yml",
49
50
  "README.md",