dsh-plugin-reverse-proxy 0.3.5 → 0.4.3

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
@@ -4,6 +4,83 @@
4
4
 
5
5
  ---
6
6
 
7
+ ## 0.4.3
8
+
9
+ 仅文档与仓库配置,代码同 0.4.2。
10
+
11
+ **更新内容**
12
+ - README 首屏加**一行安装命令**与「装完点哪儿」,徽章全部换成可点的真实链接(license / npm 版本 / 下载量 / release / CI / stars)。
13
+ - About 描述补上「内网穿透替代」「免 Token 登录」等会被搜的词,homepage 指向 npm 包页。
14
+ - 新增 `.github/workflows/publish.yml`:推 `v*` 标签自动发 npm,并校验标签与 `package.json` 版本一致。
15
+ - 新增 Issue 模板(自动带 DSH 版本 / 插件版本 / 开关状态 / 系统浏览器)与讨论区入口。
16
+
17
+ **修复内容**
18
+ - README 里 tarball 示例仍写着 0.3.5 的文件名,改成 0.4.3。
19
+
20
+ ## 0.4.2
21
+
22
+ ### 文档 / 界面
23
+ - 设置页「局域网访问」面板底部新增一条常驻提示:**多窗口限制**——同一浏览器暂时只能开一个窗口,第二块会卡在加载,原因是 DSH 官方的身份模型(一个浏览器 = 一份连接、只接一条能回答的事件流),插件层绕不过去,等官方放开;手机与电脑各开一个、或其中一个用无痕窗口不受影响。
24
+ - README 中英 FAQ 同步改成「已知限制」,不再声称已修复;同时写明 0.4.x 已经把标签身份做进 `x-dsh-tab` / `?tab=`(日志可见),卡点在网关只认一条回答流。
25
+
26
+ ## 0.4.1
27
+
28
+ **一句话:把「普通请求」也认到标签身份上——这才是多窗口卡住的真正断点。**
29
+
30
+ ### 修复
31
+ - 0.4.0 的诊断日志给出了答案:`http tab` / `http 无标签身份` **一条都没有**,说明普通请求根本没有走身份判定。原因是免 Token 模式下官方 `admit()` 里 `browserAuth.isAuthenticated()` 恒真,所有请求直接落到共享的 `browserPeer`;而事件流(waterfall)要求「回答必须来自持有该流的同一份 Peer」,`browserPeer` 手上没有 socket,请求于是永远挂起。
32
+ - 现在接管 `admit(request)`:带 `x-dsh-tab`(或 `?tab=`)的请求交给该标签自己的 Peer,与它的 mux 复用同一份;认不到标签才退回官方共享 Peer。
33
+ - mux 改成引用计数:同一标签的多条 socket 挂在同一份 Peer 上,全部断开才 dispose(0.3.x 里「新连接顶掉旧 Peer、旧 Peer 泄漏」一并解决)。
34
+ - 日志变清爽:`mux admit <tab> | 该标签 socket 数: N | 活跃 Peer: M`、`http tab <id> <path>`(每分钟每对去重)。
35
+
36
+ ## 0.4.0
37
+
38
+ ### 修复 / 诊断
39
+ - 0.3.9 之后两块窗口确实拿到了不同 id(日志 `tab-mwm0` / `tab-mwm1`),但第二块仍然卡在首屏,说明身份只是链条的第一环。
40
+ - 增加诊断日志(每分钟每个(标签, 路径)/(无标签, 路径)各一条):
41
+ - `http tab <id> /api/…`:带标签身份的普通请求;
42
+ - `http 无标签身份 /api/…`:**没带** `x-dsh-tab` 的请求(说明有代码路径绕过了签名,嫌疑最大)。
43
+ - 修 Peer 账目:同一标签反复重连时旧记录被新记录顶掉,旧记录的 release 找不到自己、Peer 永不回收(日志里「活跃 Peer」只涨不跌就是这个);现在 release 会按记录自身清理。
44
+
45
+ ## 0.3.9
46
+
47
+ ### 修复
48
+ - 0.3.8 之后两个标签仍拿到同一个身份:浏览器在「复制标签 / 从已有标签打开链接」时会把 `sessionStorage` 整份复制给新标签,于是两边的 `dsh-reproxy-tab` 完全一样(日志里 `mux admit tab-mwm0…` 两次同 id 就是它)。
49
+ - 改成只放在内存里、每个文档生成一次:一次页面加载 = 一个身份,复制标签/新开标签必然不同。刷新页面会换新 id(旧 Peer 随旧连接释放,不影响使用)。
50
+
51
+ ## 0.3.8
52
+
53
+ **一句话:把身份粒度从「一个浏览器」改成「一个标签页」,同一设备可以同时开多个窗口。**
54
+
55
+ ### 修复
56
+ - 0.3.7 之后多窗口仍卡:官方 `/connect` 的身份模型是「一个浏览器 cookie = 一个 Peer = 一条能回答 waterfall 的事件流」,同一浏览器的标签共享 cookie,第二个标签永远抢不到那条流,首屏请求等不到回答,页面一直转圈(断网重连能救回来,因为重连走了另一条路径)。
57
+ - 浏览器半边:每个标签页在 `sessionStorage` 里生成专属 id(不跨标签共享),`fetch` 加 `x-dsh-tab` 头、`WebSocket` 加 `?tab=`;挂不上或异常时静默退回原样,不影响单窗口。
58
+ - 主机半边:`multi-peer.js` 按标签 id 分配 Peer(HTTP 一元调用与 mux 复用同一份),断开即回收;认不到标签 id 时完全退回官方共享 Peer 行为。
59
+
60
+ ## 0.3.7
61
+
62
+ ### 修复
63
+ - 多窗口仍卡住:0.3.6 在铸造新 Peer 之前先走了官方 `admitConnection()`,共享 Peer 的 `ownsSocket` 被第一块窗口占住,第二块窗口直接吃到 409、客户端无限重连(表现就是一直转圈)。现在先做信任判定、再铸 Peer,不再碰共享 Peer 的 socket 归属。
64
+ - 增加多窗口诊断日志:每条 mux 连接的 admit/release、interactions 声明、活跃 Peer 数,以及被拒原因。
65
+
66
+ ## 0.3.6(2026-11-18)
67
+
68
+ **一句话:同一台设备开第二个窗口不再抢不到后台——每条连接各拿一份独立会话。**
69
+
70
+ ### 修复
71
+
72
+ - 同一设备开着第一个窗口、再开第二个窗口时,页面资源与聊天记录都加载不出来,必须把设备上所有窗口关掉才能恢复。
73
+ 根因:免 Token 模式没有身份层,`browserAuth.isAuthenticated()` 恒真 ⇒ 所有浏览器请求共用同一个 `browserPeer`,
74
+ 而一个 Peer 只服务它绑定的那条 mux 流;第二个窗口接上时两条流抢同一个 Peer,后开的就一直等不到响应。
75
+ 现在每条 mux 连接在准入时现铸一份 Peer(principal 仍是 owner,`interactions` 沿用客户端在 `/connect` 里声明的值),
76
+ 连接结束时释放——等价于官方「换一个浏览器 = 换一个会话」,只是把「浏览器」换成「连接」。
77
+
78
+ ### 更新
79
+
80
+ - 启动日志多一行 `[reproxy-lan] per-socket peers enabled (multi-window)`,便于确认这段逻辑生效。
81
+
82
+ ---
83
+
7
84
  ## 0.3.5(2026-11-17)
8
85
 
9
86
  **一句话:设置页的开关换成紫色,并新增「监听端口」输入框(保存即生效、重启保留)。**
package/README.en.md CHANGED
@@ -7,17 +7,27 @@
7
7
  <p align="center"><a href="README.md">简体中文</a> | English</p>
8
8
 
9
9
  <p align="center">
10
- <a href="#"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="license"></a>
11
- <a href="#"><img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="dependencies"></a>
12
- <a href="#"><img src="https://img.shields.io/badge/build-none-brightgreen.svg" alt="build"></a>
13
- <a href="#"><img src="https://img.shields.io/badge/dsh-0.2.2--rc.3-blueviolet.svg" alt="dsh"></a>
14
- <a href="#"><img src="https://img.shields.io/badge/status-beta-orange.svg" alt="status"></a>
10
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="license"></a>
11
+ <a href="https://www.npmjs.com/package/dsh-plugin-reverse-proxy"><img src="https://img.shields.io/npm/v/dsh-plugin-reverse-proxy?label=npm" alt="npm"></a>
12
+ <a href="https://www.npmjs.com/package/dsh-plugin-reverse-proxy"><img src="https://img.shields.io/npm/dm/dsh-plugin-reverse-proxy?label=downloads" alt="downloads"></a>
15
13
  <a href="https://github.com/llifco/dsh-plugin-reverse-proxy/releases/latest"><img src="https://img.shields.io/github/v/release/llifco/dsh-plugin-reverse-proxy?label=release" alt="release"></a>
14
+ <img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="dependencies">
15
+ <img src="https://img.shields.io/badge/build-none-brightgreen.svg" alt="build">
16
+ <a href="#scope"><img src="https://img.shields.io/badge/dsh-0.2.2--rc.1~rc.3-blueviolet.svg" alt="dsh"></a>
17
+ <a href="https://github.com/llifco/dsh-plugin-reverse-proxy/actions"><img src="https://img.shields.io/github/actions/workflow/status/llifco/dsh-plugin-reverse-proxy/publish.yml?label=publish" alt="publish"></a>
16
18
  <a href="https://github.com/llifco/dsh-plugin-reverse-proxy/stargazers"><img src="https://img.shields.io/github/stars/llifco/dsh-plugin-reverse-proxy" alt="stars"></a>
17
19
  </p>
18
20
 
19
21
  > One command and any device on your LAN — phone, tablet, another laptop — can open your DSH web UI,
20
22
  > **without copying the random token out of the startup log**.
23
+ ```bash
24
+ dsh plugin --profile web add dsh-plugin-reverse-proxy # recommended: npm package, no build
25
+ ```
26
+
27
+ Then open **Settings → LAN access**: it listens on loopback only by default, flip the switch,
28
+ confirm — your phone can connect.
29
+ (You can also install from source: `github:llifco/dsh-plugin-reverse-proxy`, see [Install](#install).)
30
+
21
31
 
22
32
  ---
23
33
 
@@ -123,16 +133,27 @@ The desktop app runs locally and can hit `127.0.0.1:3080` directly — no proxy,
123
133
 
124
134
  ## Install
125
135
 
136
+ **From npm (easiest; also listed in awesome-dsh-plugin)**
137
+
138
+ ```bash
139
+ dsh plugin --profile web add dsh-plugin-reverse-proxy
140
+ ```
141
+
142
+ or search `reverse-proxy` in the plugin marketplace and hit Install.
143
+
144
+ **From source**
145
+
126
146
  ```bash
127
147
  git clone https://github.com/llifco/dsh-plugin-reverse-proxy.git
128
148
  cd dsh-plugin-reverse-proxy
129
149
  dsh plugin --profile web add .
130
150
  ```
131
151
 
132
- or install the tarball from the releases page:
152
+ or use the tarball from the releases page / npm (filename carries the current version):
133
153
 
134
154
  ```bash
135
- dsh plugin --profile web add ./dsh-plugin-reverse-proxy-0.3.3.tgz
155
+ dsh plugin --profile web add ./dsh-plugin-reverse-proxy-0.4.3.tgz
156
+ # or: https://registry.npmjs.org/dsh-plugin-reverse-proxy/-/dsh-plugin-reverse-proxy-0.4.3.tgz
136
157
  ```
137
158
 
138
159
  Restart the host once:
@@ -222,6 +243,14 @@ No, and it should not. It only makes LAN access work; add your own tunnel plus a
222
243
  **Does the desktop app use it?**
223
244
  No — connect to `127.0.0.1:3080` directly.
224
245
 
246
+ **Q: Opening a second window on the same device shows a blank page and no chat history?**
247
+
248
+ Fixed in 0.3.6. Without an identity layer every browser request shares one
249
+ `browserPeer`, and a Peer serves only the stream bound to it — the second
250
+ window's stream competed for the same endpoints and waited forever until every
251
+ window was closed. Each mux connection now mints its own Peer. Look for
252
+ `[reproxy-lan] per-socket peers enabled (multi-window)` in the log to confirm.
253
+
225
254
  ---
226
255
 
227
256
  ## Feedback
@@ -232,3 +261,15 @@ No — connect to `127.0.0.1:3080` directly.
232
261
  ## License
233
262
 
234
263
  MIT (`vendor/skip/` code comes from @iasiv5/dsh-skip-browser-auth, also MIT).
264
+
265
+ **Q: A second tab on the same device stays on a spinner?**
266
+
267
+ **Known limitation: multiple tabs of the same browser are not supported yet.** The second tab
268
+ spins forever and shows an empty session list; closing the other tabs (or a network reconnect)
269
+ recovers it. One tab per device, or one of them in a private window, works fine.
270
+
271
+ Cause is upstream: one browser cookie = one Peer = one answering event stream, and the gateway
272
+ routes events to the single live client rather than per tab. 0.4.x already gives each tab its own
273
+ identity (`x-dsh-tab` header plus `?tab=` on the mux — visible as `http tab ...` / `mux admit ...`
274
+ in the log), but the gateway still accepts only one answering stream, so the plugin cannot work
275
+ around it.
package/README.md CHANGED
@@ -7,18 +7,27 @@
7
7
  <p align="center">简体中文 | <a href="README.en.md">English</a></p>
8
8
 
9
9
  <p align="center">
10
- <a href="#"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="license"></a>
11
- <a href="#"><img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="dependencies"></a>
12
- <a href="#"><img src="https://img.shields.io/badge/build-none-brightgreen.svg" alt="build"></a>
13
- <a href="#"><img src="https://img.shields.io/badge/dsh-0.2.2--rc.3-blueviolet.svg" alt="dsh"></a>
14
- <a href="#"><img src="https://img.shields.io/badge/status-beta-orange.svg" alt="status"></a>
10
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="license"></a>
11
+ <a href="https://www.npmjs.com/package/dsh-plugin-reverse-proxy"><img src="https://img.shields.io/npm/v/dsh-plugin-reverse-proxy?label=npm" alt="npm"></a>
12
+ <a href="https://www.npmjs.com/package/dsh-plugin-reverse-proxy"><img src="https://img.shields.io/npm/dm/dsh-plugin-reverse-proxy?label=downloads" alt="downloads"></a>
15
13
  <a href="https://github.com/llifco/dsh-plugin-reverse-proxy/releases/latest"><img src="https://img.shields.io/github/v/release/llifco/dsh-plugin-reverse-proxy?label=release" alt="release"></a>
14
+ <img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="dependencies">
15
+ <img src="https://img.shields.io/badge/build-none-brightgreen.svg" alt="build">
16
+ <a href="#适用范围"><img src="https://img.shields.io/badge/dsh-0.2.2--rc.1~rc.3-blueviolet.svg" alt="dsh"></a>
17
+ <a href="https://github.com/llifco/dsh-plugin-reverse-proxy/actions"><img src="https://img.shields.io/github/actions/workflow/status/llifco/dsh-plugin-reverse-proxy/publish.yml?label=publish" alt="publish"></a>
16
18
  <a href="https://github.com/llifco/dsh-plugin-reverse-proxy/stargazers"><img src="https://img.shields.io/github/stars/llifco/dsh-plugin-reverse-proxy" alt="stars"></a>
17
19
  </p>
18
20
 
19
21
  > 一条命令装上,局域网里的手机、平板、另一台电脑就能直接打开你的 DSH 网页界面,
20
22
  > **而且不用再从启动日志里抄那串随机 token**。
21
23
 
24
+ ```bash
25
+ dsh plugin --profile web add dsh-plugin-reverse-proxy # 推荐:npm 包,免构建
26
+ ```
27
+
28
+ 装完打开 **设置 → 局域网访问**:默认只监听本机,点开关 → 确认 → 手机就能进。
29
+ (也可以 `github:llifco/dsh-plugin-reverse-proxy` 从源码装,见 [安装](#安装)。)
30
+
22
31
  ---
23
32
 
24
33
  ## 三个能力
@@ -145,16 +154,27 @@ reproxy-lan --help
145
154
 
146
155
  ## 安装
147
156
 
157
+ **从 npm 装(最简单,已收录 awesome-dsh-plugin)**
158
+
159
+ ```bash
160
+ dsh plugin --profile web add dsh-plugin-reverse-proxy
161
+ ```
162
+
163
+ 或在插件市场里搜 `reverse-proxy`,点「安装」。
164
+
165
+ **从源码装**
166
+
148
167
  ```bash
149
168
  git clone https://github.com/llifco/dsh-plugin-reverse-proxy.git
150
169
  cd dsh-plugin-reverse-proxy
151
170
  dsh plugin --profile web add .
152
171
  ```
153
172
 
154
- 或用 Release 里的包:
173
+ 或者用 Release / npm 上的 tarball(文件名带当前版本号):
155
174
 
156
175
  ```bash
157
- dsh plugin --profile web add ./dsh-plugin-reverse-proxy-0.3.3.tgz
176
+ dsh plugin --profile web add ./dsh-plugin-reverse-proxy-0.4.3.tgz
177
+ # 或 npm 包:https://registry.npmjs.org/dsh-plugin-reverse-proxy/-/dsh-plugin-reverse-proxy-0.4.3.tgz
158
178
  ```
159
179
 
160
180
  装完重启一次宿主:
@@ -250,6 +270,18 @@ nginx -t && systemctl reload nginx
250
270
  而且 80 是最容易被局域网里乱扫描的设备撞上的端口,安全上不划算。想改这段门槛,
251
271
  得改 `lan-access.js` 的 `validatePort()` 并确保进程有绑定特权端口的权限。
252
272
 
273
+ **Q:同一台设备开第二个窗口,资源和聊天记录都加载不出来?**
274
+
275
+ **当前已知限制:暂时不支持同一浏览器开多个窗口。** 第二块窗口会一直转圈、聊天记录空着,
276
+ 关掉其他窗口(或断网重连)才恢复;手机和电脑各开一个、或其中一个用无痕窗口不受影响。
277
+
278
+ 原因在 DSH 官方的身份模型:一个浏览器 cookie = 一份 Peer = 一条能回答 waterfall 的事件流,
279
+ 网关转发事件时认的是「一个活着的客户端」而不是「一个标签」。本插件 0.4.x 已经给每个标签页
280
+ 单独发了身份(`x-dsh-tab` 头 + mux 上的 `?tab=`,日志里能看到 `http tab …` / `mux admit …`
281
+ 分别是不同的 id),但网关那一层仍只认一条回答流,所以插件侧绕不过去,得等官方放开。
282
+
283
+ 设置页的「局域网访问」面板里也写了这条提示,免得下次又当故障排查。
284
+
253
285
  **Q:装完 8080 还是打不开?**
254
286
  `ss -ltnp | grep 8080` 看占用者。还是 nginx 的话,旧的 `sites-enabled/dsh` 软链没删,两个会抢端口。
255
287
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-plugin-reverse-proxy",
3
- "version": "0.3.5",
4
- "description": "DSH Web 反向代理 + 免 Token 登录(Web UI 专用):监听局域网端口,改写 Host/Origin/Sec-Fetch-Site 后转发到 127.0.0.1:3080,并替换官方 Connection 提供方跳过 BrowserAuth(版本门控,不匹配自动休眠)。仅适用于 Web UI 版,桌面版用不上。",
3
+ "version": "0.4.3",
4
+ "description": "DSH 网页界面局域网访问插件:内置反向代理 + 免 Token 登录,手机/平板同 Wi-Fi 直接打开后台。默认只监听本机,需显式开启,端口可自定义。",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "exports": {
@@ -1,4 +1,5 @@
1
1
  import { bridgeWithPeer } from '../bridge.js';
2
+ import { installPerSocketPeers } from '../multi-peer.js';
2
3
  /**
3
4
  * Host implementation for the 0.2.1 carrier-neutral connection contract.
4
5
  *
@@ -39,6 +40,12 @@ export function createCarrierNeutral021Runtime(input) {
39
40
  if (typeof fetchHandler.requestBodyMode !== 'function') {
40
41
  throw new Error('dsh-plugin-reverse-proxy: carrier-neutral-021 profile requires a requestBodyMode-aware connection handler');
41
42
  }
43
+ // 多窗口:trusted 模式没有身份层,所有浏览器请求共享 browserPeer;给每条
44
+ // mux 连接现铸一份 Peer,否则第二个窗口会和第一个抢同一份流端点(见
45
+ // vendor/skip/multi-peer.js 顶部说明)。
46
+ if (installPerSocketPeers(connection)) {
47
+ console.log('[reproxy-lan] per-socket peers enabled (multi-window)');
48
+ }
42
49
  const waterfall = input.ctx.waterfall;
43
50
  if (typeof waterfall !== 'function') {
44
51
  throw new Error('dsh-plugin-reverse-proxy: carrier-neutral-021 profile requires a waterfall-capable carrier context');
@@ -11,6 +11,84 @@ window.__ModuleLoader__.load({
11
11
  },
12
12
  });
13
13
  const profile = globalThis["__DSH_SKIP_BROWSER_AUTH_PROFILE__"];
14
+ // ── 标签身份(0.3.8)────────────────────────────────────────────────────
15
+ // 同一浏览器的多个标签页共用一个 cookie,官方身份层因此把它们当成同一个
16
+ // Peer;而一份 Peer 只绑一条能回答 waterfall 的事件流,第二个标签的首屏
17
+ // 请求就等不到回答、一直转圈。这里给每个标签页发一个只属于它的 id
18
+ // (sessionStorage 不跨标签共享),请求带 x-dsh-tab、WebSocket 带 ?tab=,
19
+ // 宿主侧据此各给一份 Peer。挂不上或出错就静默放行,绝不阻断页面启动。
20
+ const installTabIdentity = () => {
21
+ const KEY = 'dsh-reproxy-tab'
22
+ const HEADER = 'x-dsh-tab'
23
+ const VALID = /^[A-Za-z0-9._-]{8,64}$/
24
+ // 只放在内存里,每个文档一份:sessionStorage 在「复制标签/从链接打开」时
25
+ // 会被浏览器整份复制给新标签,两个标签就会拿到同一个 id(实测同 id 前缀
26
+ // tab-mwm0…),等于没修。内存变量天然是「一次页面加载 = 一个身份」。
27
+ let id
28
+ try {
29
+ const raw = (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')
30
+ ? crypto.randomUUID()
31
+ : 'tab-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10)
32
+ id = raw.replace(/[^A-Za-z0-9._-]/g, '').slice(0, 64)
33
+ }
34
+ catch {
35
+ return
36
+ }
37
+ if (!id || !VALID.test(id)) return
38
+ const origin = typeof location === 'undefined' ? undefined : location.origin
39
+ const originalFetch = globalThis.fetch
40
+ if (typeof originalFetch === 'function' && originalFetch.__reproxyTab !== true) {
41
+ const fetchWithTab = function (input, init) {
42
+ try {
43
+ const raw = typeof input === 'string' ? input : (input instanceof Request ? input.url : String(input))
44
+ const abs = new URL(raw, origin ?? 'http://dsh.invalid')
45
+ if (origin === undefined || abs.origin === origin) {
46
+ const headers = new Headers(init && init.headers !== undefined ? init.headers : (input instanceof Request ? input.headers : undefined))
47
+ headers.set(HEADER, id)
48
+ const target = input instanceof Request ? new Request(input, { headers }) : input
49
+ return originalFetch.call(this, target, Object.assign({}, init, { headers }))
50
+ }
51
+ }
52
+ catch {
53
+ // 任何形态异常都退回原样调用
54
+ }
55
+ return originalFetch.apply(this, arguments)
56
+ }
57
+ fetchWithTab.__reproxyTab = true
58
+ globalThis.fetch = fetchWithTab
59
+ }
60
+ const OriginalSocket = globalThis.WebSocket
61
+ if (typeof OriginalSocket === 'function' && OriginalSocket.__reproxyTab !== true) {
62
+ const socketWithTab = function (url, protocols) {
63
+ let target = url
64
+ try {
65
+ const abs = new URL(String(url), origin ?? 'http://dsh.invalid')
66
+ abs.searchParams.set('tab', id)
67
+ target = abs.href
68
+ }
69
+ catch {
70
+ // 解析失败就用原 URL
71
+ }
72
+ return protocols === undefined ? new OriginalSocket(target) : new OriginalSocket(target, protocols)
73
+ }
74
+ socketWithTab.__reproxyTab = true
75
+ socketWithTab.prototype = OriginalSocket.prototype
76
+ try {
77
+ Object.setPrototypeOf(socketWithTab, OriginalSocket)
78
+ }
79
+ catch {
80
+ // 静态常量挂在原构造器上,拷不过来也不影响实例
81
+ }
82
+ globalThis.WebSocket = socketWithTab
83
+ }
84
+ console.log('[reproxy-lan] tab identity =', id.slice(0, 8))
85
+ };
86
+ try {
87
+ installTabIdentity();
88
+ }
89
+ catch (error) {
90
+ console.warn('[reproxy-lan] tab identity failed', error);
91
+ }
14
92
  const LAN_WARNING_TITLE = '对局域网开放访问?';
15
93
  const LAN_WARNING_LINES = [
16
94
  '开启后,同一网络里的任何设备打开这台机器的 8080 端口,都能直接进入 DSH 后台,',
@@ -38,6 +116,8 @@ window.__ModuleLoader__.load({
38
116
  '.reproxy-lan-ok{font-size:12px;color:#5ee08a}',
39
117
  '.reproxy-lan-switch[disabled]{opacity:.55;cursor:default}',
40
118
  '.reproxy-lan-meta{font-size:12px;color:var(--dsw-alias-label-secondary,#9aa0ad);line-height:1.7}',
119
+ '.reproxy-lan-note{margin-top:10px;padding:8px 10px;border-radius:8px;font-size:12px;line-height:1.75;color:var(--dsw-alias-label-secondary,#9aa0ad);background:rgba(255,255,255,.04);border:1px solid var(--dsw-alias-border-l1,#333947)}',
120
+ '.reproxy-lan-note b{color:var(--dsw-alias-label-primary,#e8ebf2);font-weight:600}',
41
121
  '.reproxy-lan-err{font-size:12px;color:#ff6b6b}',
42
122
  '.reproxy-lan-mask{position:fixed;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:9999}',
43
123
  '.reproxy-lan-card{width:min(460px,92vw);background:var(--dsw-alias-bg-layer-1,#1c1f26);border:1px solid rgba(255,255,255,.12);border-radius:12px;padding:20px;box-shadow:0 18px 48px rgba(0,0,0,.45)}',
@@ -157,6 +237,13 @@ window.__ModuleLoader__.load({
157
237
  portMsg ? h('div', { className: portBad ? 'reproxy-lan-err' : 'reproxy-lan-ok' }, portMsg) : null,
158
238
  h('div', { className: 'reproxy-lan-meta' }, status),
159
239
  state && state.updatedAt ? h('div', { className: 'reproxy-lan-meta' }, '上次修改:' + state.updatedAt + '(' + (state.updatedBy || 'unknown') + ')') : null,
240
+ h('div', { className: 'reproxy-lan-note' },
241
+ h('b', null, '多窗口限制:'),
242
+ '同一浏览器暂时只能开一个窗口访问——第二块窗口会卡在加载、聊天记录出不来,',
243
+ '关掉其他窗口或断网重连才会恢复。这是 DSH 官方的身份模型(一个浏览器 = 一份连接,',
244
+ '只接一条能回答的事件流),插件层绕不过去,要等官方放开;',
245
+ '手机和电脑各开一个、或其中一个用无痕窗口,都不受影响。'
246
+ ),
160
247
  error ? h('div', { className: 'reproxy-lan-err' }, error) : null,
161
248
  asking ? h('div', { className: 'reproxy-lan-mask' },
162
249
  h('div', { className: 'reproxy-lan-card' },
@@ -0,0 +1,141 @@
1
+ /**
2
+ * 多窗口共存:每个标签页自己的身份 ⇒ 每个标签页自己的 Peer。
3
+ *
4
+ * 官方 ConnectionService 的身份模型是「一个浏览器 cookie = 一个 Peer」:同一
5
+ * 浏览器的所有标签共享 cookie,于是第二块窗口和第一块抢同一个 Peer;而官方一个
6
+ * Peer 只认一条事件流(能回答 waterfall 的那条),第二块窗口的首屏请求等不到
7
+ * 回答,就一直转圈。
8
+ *
9
+ * 免 Token 模式更麻烦一层:官方 `admit()` 里 `isAuthenticated()` 恒真,于是所有
10
+ * 普通请求都直接落到共享的 `browserPeer`;事件流(waterfall)要求「回答来自持有
11
+ * 该流的同一份 Peer」,browserPeer 手上没有 socket,请求就永远没人应答。
12
+ *
13
+ * 所以这里同时接管两处:
14
+ * · `admit(request)` —— 带标签身份的请求发给该标签的 Peer(普通请求与事件流同一份);
15
+ * · `admitConnection(req)`—— mux 建立时把 socket 挂到该标签的 Peer 上,引用计数归零才回收。
16
+ * 认不到标签 id 时完全退回官方行为。
17
+ */
18
+
19
+ const TAB_HEADER = 'x-dsh-tab'
20
+ const TAB_QUERY = 'tab'
21
+ const TAB_PATTERN = /^[A-Za-z0-9._-]{8,64}$/
22
+
23
+ /** 从请求里认领标签 id:优先请求头,其次 mux URL 的 ?tab=。 */
24
+ function tabIdOf(request) {
25
+ try {
26
+ const header = request?.headers?.[TAB_HEADER]
27
+ const value = Array.isArray(header) ? header[0] : header
28
+ if (typeof value === 'string' && TAB_PATTERN.test(value)) return value
29
+ const url = new URL(request?.url ?? '/', 'http://dsh.invalid')
30
+ const query = url.searchParams.get(TAB_QUERY)
31
+ if (typeof query === 'string' && TAB_PATTERN.test(query)) return query
32
+ }
33
+ catch {
34
+ // 请求形态异常一律当作「没有标签身份」,走官方路径
35
+ }
36
+ return undefined
37
+ }
38
+
39
+ function pathOf(request) {
40
+ try { return new URL(request?.url ?? '/', 'http://dsh.invalid').pathname }
41
+ catch { return '?' }
42
+ }
43
+
44
+ /**
45
+ * 在 ConnectionService 实例上安装 per-tab Peer 行为。
46
+ * @param connection - 官方 HostConnectionService 实例(已由适配器创建)
47
+ * @returns 是否安装成功
48
+ */
49
+ export function installPerSocketPeers(connection) {
50
+ const peers = connection.peers
51
+ const publishPeer = connection.publishPeer
52
+ if (!(peers instanceof Map) || typeof publishPeer !== 'function') return false
53
+ if (typeof connection.admit !== 'function' || typeof connection.admitConnection !== 'function') return false
54
+
55
+ const originalAdmit = connection.admit.bind(connection)
56
+ const originalAdmitConnection = connection.admitConnection.bind(connection)
57
+
58
+ /** tab → { record, sockets } ;sockets 是该标签当前挂着的 mux 数。 */
59
+ const tabs = new Map()
60
+ const seen = new Map()
61
+ const logOnce = (key, line) => {
62
+ const bucket = Math.floor(Date.now() / 60000)
63
+ const k = `${key}:${bucket}`
64
+ if (seen.has(k)) return
65
+ seen.set(k, true)
66
+ if (seen.size > 400) seen.clear()
67
+ console.log(line)
68
+ }
69
+
70
+ function mint(key, interactions) {
71
+ const id = publishPeer.call(connection, interactions ?? 'answer')
72
+ const record = peers.get(id)
73
+ if (record === undefined) return undefined
74
+ if (key !== id) {
75
+ peers.delete(id)
76
+ peers.set(key, record)
77
+ }
78
+ // 让 record 自己知道它挂在哪个 key 下,回收时才能找到自己
79
+ record.__reproxyKey = key
80
+ return record
81
+ }
82
+
83
+ function ensure(tab) {
84
+ let entry = tabs.get(tab)
85
+ if (entry !== undefined && entry.record?.peer !== undefined) return entry
86
+ const record = mint(tab, 'answer')
87
+ if (record === undefined) return undefined
88
+ entry = { record, sockets: 0 }
89
+ tabs.set(tab, entry)
90
+ return entry
91
+ }
92
+
93
+ // ① 普通请求:官方在免 Token 模式下把所有人都塞给 browserPeer,
94
+ // 这里先把标签认出来,再交给该标签自己的 Peer。
95
+ connection.admit = function admitPerTab(request) {
96
+ const base = originalAdmit(request)
97
+ if (base !== undefined && base !== null && 'rejection' in base) return base
98
+ const tab = tabIdOf(request)
99
+ if (tab === undefined) return base
100
+ const entry = ensure(tab)
101
+ if (entry === undefined) return base
102
+ logOnce(`http:${tab}`, `[reproxy-lan] http tab ${tab.slice(0, 8)} ${pathOf(request)}`)
103
+ return { peer: entry.record.peer }
104
+ }
105
+
106
+ // ② mux:socket 挂到同一份 Peer 上,引用计数归零才 dispose。
107
+ connection.admitConnection = function admitConnectionPerTab(request) {
108
+ const tab = tabIdOf(request)
109
+ if (tab === undefined) return originalAdmitConnection(request)
110
+ const base = originalAdmit(request)
111
+ if (base !== undefined && base !== null && 'rejection' in base) {
112
+ logOnce(`muxrej:${tab}`, `[reproxy-lan] mux 被拒 ${tab.slice(0, 8)} → ${base.rejection}`)
113
+ return base
114
+ }
115
+ const entry = ensure(tab)
116
+ if (entry === undefined) return originalAdmitConnection(request)
117
+ entry.sockets += 1
118
+ entry.record.ownsSocket = true
119
+ let released
120
+ console.log('[reproxy-lan] mux admit', tab.slice(0, 8), '| 该标签 socket 数:', entry.sockets, '| 活跃 Peer:', peers.size)
121
+ return {
122
+ peer: entry.record.peer,
123
+ release: () => {
124
+ if (released !== undefined) return released
125
+ entry.sockets = Math.max(0, entry.sockets - 1)
126
+ let disposed
127
+ if (entry.sockets === 0) {
128
+ if (peers.get(tab) === entry.record) peers.delete(tab)
129
+ else if (entry.record.peer !== undefined && peers.get(entry.record.peer.id) === entry.record) peers.delete(entry.record.peer.id)
130
+ tabs.delete(tab)
131
+ disposed = entry.record.peer.dispose()
132
+ }
133
+ else disposed = Promise.resolve()
134
+ console.log('[reproxy-lan] mux release', tab.slice(0, 8), '| 该标签 socket 数:', entry.sockets, '| 剩余 Peer:', peers.size)
135
+ released = disposed
136
+ return released
137
+ },
138
+ }
139
+ }
140
+ return true
141
+ }