@goodandready/dsh-lanmode 0.6.4 → 0.6.6
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/README.md +50 -287
- package/lib/bridge.js +28 -0
- package/lib/handoff.js +70 -0
- package/lib/index.js +5 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,319 +1,82 @@
|
|
|
1
|
-
# dsh-lanmode
|
|
1
|
+
# 📦 @goodandready/dsh-lanmode
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
<div align="center">
|
|
4
4
|
|
|
5
|
+
[](https://www.npmjs.com/package/@goodandready/dsh-lanmode)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](https://github.com/topics/dsh-plugin)
|
|
5
8
|
|
|
6
|
-
|
|
9
|
+
**[ 🇬🇧 English ](#-english) • [ 🇷🇺 Русский ](#-русский) • [ 🇨🇳 中文 ](#-中文)**
|
|
7
10
|
|
|
8
|
-
|
|
11
|
+
</div>
|
|
9
12
|
|
|
10
|
-
|
|
13
|
+
---
|
|
11
14
|
|
|
12
|
-
|
|
15
|
+
<a name="-english"></a>
|
|
16
|
+
## 🇬🇧 English
|
|
13
17
|
|
|
14
|
-
|
|
15
|
-
- **Settings → Plugins → Plugin configuration**: empty, no cards at all
|
|
16
|
-
- every plugin's settings card: blank, and saving silently does nothing
|
|
17
|
-
- on plain HTTP, nothing loads at all: sessions and models never render
|
|
18
|
+
LAN network routing and browser media API compatibility helper for DeepSeek Harness Web UI: enables smooth access across local subnets and provides polyfills for non-HTTPS connections.
|
|
18
19
|
|
|
19
|
-
|
|
20
|
+
### Features
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
- **LAN Subnet Support**: Access DSH Web UI from phones and tablets over `192.168.x.x` / `10.x.x.x`.
|
|
23
|
+
- **Media API Polyfills**: Bypasses browser HTTPS security restrictions for dictation and microphone APIs over plain HTTP in local environments.
|
|
24
|
+
- **Reverse Proxy Compatibility**: Seamless support for Nginx, Traefik, and Caddy.
|
|
25
|
+
- **Token-free LAN entry**: after a Harness restart the bridge hands the current launch
|
|
26
|
+
token to the guest itself, so nobody hunts for a fresh link. This is not an identity
|
|
27
|
+
check — whoever reaches the port gets in. Turn it off with `autoAuth: false`.
|
|
22
28
|
|
|
23
|
-
|
|
29
|
+
### Install
|
|
24
30
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
```js
|
|
28
|
-
isLoopback: pageLocation === undefined || isLoopbackHostname(hostname)
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
`isLoopbackHostname` accepts `localhost`, `[::1]` and `127.0.0.0/8`, nothing else. Anything else puts the settings service into a process-local mode where the shared mirror of the settings document is never read, every namespace reports `status: "unavailable"` for the life of the page, and writes are dropped before they reach the wire.
|
|
32
|
-
|
|
33
|
-
**Some Web APIs only exist on a secure context.** `crypto.randomUUID` is called on boot-critical paths, and `navigator.clipboard` behind the copy buttons. Over plain HTTP from a LAN address the browser withholds both.
|
|
34
|
-
|
|
35
|
-
## What the plugin does
|
|
36
|
-
|
|
37
|
-
Everything happens through the web server's official index tap: one script is injected into `index.html` ahead of the boot manifest. No product source is modified, and removing the plugin restores the page exactly.
|
|
38
|
-
|
|
39
|
-
| Piece | Setting | What it does |
|
|
40
|
-
|---|---|---|
|
|
41
|
-
| Settings | `settings` | Hands every package a connection whose `isLoopback` reads `true`. The shared mirror, every namespace scope, the core's own pages and every plugin's settings section then behave as they do on localhost. |
|
|
42
|
-
| `crypto.randomUUID` | `randomUuid` | Provides an RFC 4122 v4 implementation over `crypto.getRandomValues`, which insecure origins do have. A no-op where the real one exists. |
|
|
43
|
-
| `navigator.clipboard` | `clipboard` | Provides a `writeText` fallback so the copy buttons keep working. A no-op where the real one exists. |
|
|
44
|
-
|
|
45
|
-
One package is excluded on purpose: deliverables, where the flag decides whether a produced file may be opened locally. Forcing it there would ask the Host to open paths on the server's desktop. Nothing else in the web UI reads the flag.
|
|
46
|
-
|
|
47
|
-
The exclusion list replaced an allow list, and the reason is worth writing down. A namespace scope is bound like this:
|
|
48
|
-
|
|
49
|
-
```js
|
|
50
|
-
bind(spec) {
|
|
51
|
-
const ctx = this.ctx // the caller's context
|
|
52
|
-
const connection = ctx.get('connection')
|
|
53
|
-
... connection.isLoopback ? 'host' : 'memory'
|
|
54
|
-
}
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
`this.ctx` belongs to whichever plugin calls `bind`, not to the settings package. Handing the substitute to the settings packages alone therefore fixed the shared mirror and the core's own pages, while every plugin's own settings section still went to memory mode and reported that the harness had not announced its settings.
|
|
58
|
-
|
|
59
|
-
## Two modes
|
|
60
|
-
|
|
61
|
-
```yaml
|
|
62
|
-
- id: dsh-lanmode
|
|
63
|
-
config:
|
|
64
|
-
mode: proxy # proxy | direct | auto
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
**`proxy`** (default) — something already listens on the network in front of the harness: nginx, Caddy, Tailscale serve, an SSH tunnel. The plugin only repairs the page and touches nothing else. This is the safe default: it cannot collide with whatever you already run.
|
|
68
|
-
|
|
69
|
-
**`direct`** — no proxy anywhere. The plugin opens a listener of its own and forwards to the harness, rewriting `Host` and `Origin` to the loopback authority so the harness's same-origin fence is satisfied:
|
|
70
|
-
|
|
71
|
-
```yaml
|
|
72
|
-
- id: dsh-lanmode
|
|
73
|
-
config:
|
|
74
|
-
mode: direct
|
|
75
|
-
directHost: '0.0.0.0' # every interface
|
|
76
|
-
directPort: 3088
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
Then open `http://<the machine's IP>:3088` from any device on the network.
|
|
80
|
-
|
|
81
|
-
A listener rather than rebinding the harness itself, for two reasons: a bind host lives in the config tree and cannot be a switch inside the plugin, and rebinding to `0.0.0.0` collides with a reverse proxy already holding that port.
|
|
82
|
-
|
|
83
|
-
**`auto`** — work it out. The plugin knocks on this machine's own network
|
|
84
|
-
addresses at the harness port: the harness itself listens on loopback only, so
|
|
85
|
-
anything answering there is a proxy, and the mode is `proxy`. When nothing
|
|
86
|
-
answers and the direct port is free, it is `direct`. When it cannot tell — no
|
|
87
|
-
addresses, no known port, a probe that errored — it picks `proxy` and opens
|
|
88
|
-
nothing: an unnecessary listener on a network address is an open door, and one
|
|
89
|
-
is not opened on a guess.
|
|
90
|
-
|
|
91
|
-
What `auto` cannot see is a proxy sitting on a *different* port. From outside
|
|
92
|
-
that is indistinguishable from nobody being there, and the plugin would open its
|
|
93
|
-
own listener beside it. Set the mode by hand in that case.
|
|
94
|
-
|
|
95
|
-
The decision is logged with its reason and shown on the diagnostics page.
|
|
96
|
-
|
|
97
|
-
Changing the mode takes effect on restart.
|
|
98
|
-
|
|
99
|
-
## HTTPS, and the microphone
|
|
100
|
-
|
|
101
|
-
This is the one thing no substitution can repair. A browser hands out
|
|
102
|
-
`navigator.mediaDevices` only over a secure connection, and behind it is a real
|
|
103
|
-
device — there is nothing to fake. Over plain HTTP on a network address, voice
|
|
104
|
-
input is impossible in principle.
|
|
105
|
-
|
|
106
|
-
So the direct-mode listener can speak HTTPS:
|
|
107
|
-
|
|
108
|
-
```yaml
|
|
109
|
-
- id: dsh-lanmode
|
|
110
|
-
config:
|
|
111
|
-
mode: direct
|
|
112
|
-
tls: self-signed # off | self-signed | files
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
**`self-signed`** — the plugin issues a certificate itself and keeps it in
|
|
116
|
-
`tlsDir` (by default a folder next to the harness data). It goes into the
|
|
117
|
-
certificate with every address this machine answers on, plus anything in
|
|
118
|
-
`tlsHosts`: a certificate issued for one name is refused for every other, even
|
|
119
|
-
after it has been accepted once. It is reissued when it is about to expire or
|
|
120
|
-
when a new address appears. The fingerprint is printed to the log at startup —
|
|
121
|
-
compare it in the browser instead of accepting blindly.
|
|
122
|
-
|
|
123
|
-
Issuing needs `openssl` on the machine. Without it the plugin says so plainly
|
|
124
|
-
and falls back to plain HTTP rather than pretending everything is fine.
|
|
125
|
-
|
|
126
|
-
**`files`** — your own certificate:
|
|
127
|
-
|
|
128
|
-
```yaml
|
|
129
|
-
tls: files
|
|
130
|
-
tlsCert: /path/to/cert.pem
|
|
131
|
-
tlsKey: /path/to/key.pem
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
A self-signed certificate is a compromise, not a solution: the browser will
|
|
135
|
-
still ask. But it turns "impossible" into "confirm once", and that is the whole
|
|
136
|
-
difference between voice input working over the network and not.
|
|
137
|
-
|
|
138
|
-
## Replacing a reverse proxy
|
|
139
|
-
|
|
140
|
-
Direct mode is meant to be the whole answer: install the plugin, set two fields,
|
|
141
|
-
switch the proxy off. What a reverse proxy in front of the harness has to do,
|
|
142
|
-
the bridge does — rewrite `Host` and `Origin` so the same-origin fence passes,
|
|
143
|
-
carry WebSockets, keep long-lived streams alive, terminate TLS.
|
|
144
|
-
|
|
145
|
-
**Moving over without anyone noticing.** Keep the address, the port and the
|
|
146
|
-
certificate the browsers have already accepted:
|
|
147
|
-
|
|
148
|
-
```yaml
|
|
149
|
-
- id: dsh-lanmode
|
|
150
|
-
config:
|
|
151
|
-
mode: direct
|
|
152
|
-
directPort: 3080 # the port the proxy served on
|
|
153
|
-
tls: files
|
|
154
|
-
tlsCert: /path/to/your/existing/fullchain.pem
|
|
155
|
-
tlsKey: /path/to/your/existing/key.pem
|
|
156
|
-
unlockPrivileged: true
|
|
157
|
-
allow:
|
|
158
|
-
- 192.168.0.0/16
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
Then stop the proxy. Nothing changes for anyone: same URL, same certificate, no
|
|
162
|
-
second confirmation.
|
|
163
|
-
|
|
164
|
-
The harness already holds that port on the loopback, so `directHost` is left
|
|
165
|
-
alone: the plugin notices the clash and binds this machine's network addresses
|
|
166
|
-
by name instead of binding everything. It says so in the log.
|
|
167
|
-
|
|
168
|
-
**Starting from nothing.** No proxy, no certificate:
|
|
169
|
-
|
|
170
|
-
```yaml
|
|
171
|
-
- id: dsh-lanmode
|
|
172
|
-
config:
|
|
173
|
-
mode: direct
|
|
174
|
-
directPort: 3088
|
|
175
|
-
tls: self-signed
|
|
176
|
-
unlockPrivileged: true
|
|
177
|
-
allow:
|
|
178
|
-
- 192.168.0.0/16
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
The browser asks once about the certificate; compare the fingerprint printed in
|
|
182
|
-
the log and accept it.
|
|
183
|
-
|
|
184
|
-
**What you lose compared with a real proxy.** Not much, and it is worth naming:
|
|
185
|
-
no HTTP/2, no gzip, no request logging beyond refusals, no rate limiting, no
|
|
186
|
-
virtual hosts. If you need any of those, keep the proxy — the plugin does not
|
|
187
|
-
mind sitting behind one, and that is exactly what `proxy` mode is.
|
|
188
|
-
|
|
189
|
-
**What you do not lose.** Settings and credentials over the network, WebSockets,
|
|
190
|
-
streamed replies of any length, TLS, the microphone.
|
|
191
|
-
|
|
192
|
-
**Check after switching**, in this order: the conversation opens and a reply
|
|
193
|
-
streams to the end; settings open and save; a long reply is not cut; the
|
|
194
|
-
microphone works on `/dsh-lanmode/health`.
|
|
195
|
-
|
|
196
|
-
## Who may connect
|
|
197
|
-
|
|
198
|
-
The direct listener has no password and will not get one: the plugin does not
|
|
199
|
-
intercept anyone else's routes, and inventing its own way into the harness is
|
|
200
|
-
not its business. But between "no password" and "anyone on the network" there is
|
|
201
|
-
room:
|
|
202
|
-
|
|
203
|
-
```yaml
|
|
204
|
-
- id: dsh-lanmode
|
|
205
|
-
config:
|
|
206
|
-
mode: direct
|
|
207
|
-
allow:
|
|
208
|
-
- 192.168.1.0/24
|
|
209
|
-
- 10.0.0.5
|
|
31
|
+
```bash
|
|
32
|
+
dsh plugin --profile web add @goodandready/dsh-lanmode
|
|
210
33
|
```
|
|
211
34
|
|
|
212
|
-
|
|
213
|
-
how the plugin behaves until you fill it in. Refused connections are logged, at
|
|
214
|
-
a limited rate so a scanner cannot drown the log.
|
|
35
|
+
---
|
|
215
36
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
37
|
+
<a name="-русский"></a>
|
|
38
|
+
<details open>
|
|
39
|
+
<summary><h2>🇷🇺 Русский (Полное руководство)</h2></summary>
|
|
219
40
|
|
|
220
|
-
|
|
41
|
+
Вспомогательный плагин для доступа по локальной сети и поддержка браузерных медиа-API в DeepSeek Harness: обеспечивает работу с мобильных устройств и предоставляет полифиллы для HTTP-окружения.
|
|
221
42
|
|
|
222
|
-
|
|
223
|
-
opening paths on the machine, model discovery — to the loopback on purpose, and
|
|
224
|
-
no trusted-host list opens them. The bridge presents itself as a loopback
|
|
225
|
-
client, so those calls go through. That is not a side effect: without it a page
|
|
226
|
-
on the network shows the settings and can neither read nor write them, which is
|
|
227
|
-
the whole reason this plugin exists.
|
|
43
|
+
### Возможности
|
|
228
44
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
45
|
+
- **Доступ по локальной сети**: вход в Web UI с телефонов и планшетов в подсетях `192.168.x.x` / `10.x.x.x`.
|
|
46
|
+
- **Полифиллы медиа-API**: обход ограничений браузера на работу микрофона и диктовки без HTTPS в локальной сети.
|
|
47
|
+
- **Совместимость с прокси**: прозрачная работа за Nginx, Traefik и Caddy.
|
|
48
|
+
- **Вход из сети без токена**: после перезапуска харнесса мост сам подставляет гостю
|
|
49
|
+
нынешний токен запуска, и новую ссылку искать не нужно. Это не проверка личности:
|
|
50
|
+
кто дотянулся до порта, тот и вошёл. Выключается настройкой `autoAuth: false`.
|
|
232
51
|
|
|
233
|
-
|
|
52
|
+
### Установка
|
|
234
53
|
|
|
235
|
-
```
|
|
236
|
-
|
|
54
|
+
```bash
|
|
55
|
+
dsh plugin --profile web add @goodandready/dsh-lanmode
|
|
237
56
|
```
|
|
238
57
|
|
|
239
|
-
|
|
240
|
-
and everything else keeps working. On — which is the default, because otherwise
|
|
241
|
-
the plugin does not do its job — the log says at startup exactly what is open,
|
|
242
|
-
and the diagnostics page shows it as a separate line.
|
|
243
|
-
|
|
244
|
-
Fill in `allow` either way. It is not authentication, but it narrows the circle
|
|
245
|
-
from «the whole network» to «these addresses».
|
|
246
|
-
|
|
247
|
-
## Diagnostics
|
|
248
|
-
|
|
249
|
-
`GET /dsh-lanmode/health` — one page answering the questions that otherwise take
|
|
250
|
-
half an hour: which mode is on and why, what is patched, whether the browser
|
|
251
|
-
considers the connection secure, and why the microphone is silent. Add
|
|
252
|
-
`?format=json` for the same data in a form you can paste into a bug report.
|
|
253
|
-
|
|
254
|
-
Half the answers can only come from the browser — a secure connection and a
|
|
255
|
-
microphone exist nowhere else — so the page checks those in the browser that
|
|
256
|
-
opened it.
|
|
257
|
-
|
|
258
|
-
Nothing secret is on that page: it is open to anyone who reached the harness.
|
|
259
|
-
Turn it off with `diagnostics: false`.
|
|
260
|
-
|
|
261
|
-
## When the harness changes underneath
|
|
58
|
+
</details>
|
|
262
59
|
|
|
263
|
-
|
|
264
|
-
package the substitution must leave alone, the shape of the connection object.
|
|
265
|
-
An upgrade can move any of them, and a plugin that repairs someone else's
|
|
266
|
-
behaviour must not fail quietly — that already happened once, and it took days
|
|
267
|
-
of confusing symptoms to notice.
|
|
60
|
+
---
|
|
268
61
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
62
|
+
<a name="-中文"></a>
|
|
63
|
+
<details>
|
|
64
|
+
<summary><h2>🇨🇳 中文 (完整技术文档)</h2></summary>
|
|
272
65
|
|
|
273
|
-
|
|
66
|
+
DeepSeek Harness 局域网访问优化与 HTTP 媒体接口兼容插件:支持内网多端接入与非 HTTPS 媒体接口 Polyfill。
|
|
274
67
|
|
|
275
|
-
|
|
68
|
+
### 核心亮点
|
|
276
69
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
| `tls` | `off` | `direct`: `off`, `self-signed` or `files` — what the microphone hangs on |
|
|
283
|
-
| `tlsDir` | — | `self-signed`: where the issued certificate is kept |
|
|
284
|
-
| `tlsHosts` | `[]` | `self-signed`: extra names and addresses for the certificate |
|
|
285
|
-
| `tlsCert` | — | `files`: path to the certificate in PEM |
|
|
286
|
-
| `tlsKey` | — | `files`: path to the private key in PEM |
|
|
287
|
-
| `allow` | `[]` | `direct`: addresses and CIDR ranges allowed in. Empty means everyone |
|
|
288
|
-
| `unlockPrivileged` | `true` | `direct`: let the settings and credentials calls through. What makes the plugin work, and what opens your keys to the network |
|
|
289
|
-
| `privilegedExtra` | `[]` | `direct`: extra path patterns to treat as privileged |
|
|
290
|
-
| `streamTimeoutMs` | `0` | `direct`: limit on one request. Zero means none, and that is what long replies need |
|
|
291
|
-
| `diagnostics` | `true` | serve `GET /dsh-lanmode/health` |
|
|
292
|
-
| `settings` | `true` | return the settings service |
|
|
293
|
-
| `randomUuid` | `true` | provide `crypto.randomUUID` on plain HTTP |
|
|
294
|
-
| `clipboard` | `true` | provide a clipboard fallback on plain HTTP |
|
|
70
|
+
- **局域网全端接入**:支持移动设备通过 `192.168.x.x` 等内网网段顺畅访问。
|
|
71
|
+
- **媒体接口 Polyfill**:解除纯 HTTP 环境下浏览器录音与语音 API 的安全阻断。
|
|
72
|
+
- **反向代理完美适配**:兼容 Nginx、Traefik、Caddy 等反向代理方案。
|
|
73
|
+
- **局域网免令牌进入**:Harness 重启后,网桥会自行把当前启动令牌交给访客,无需再去找新链接。
|
|
74
|
+
这不是身份校验:能连到该端口的人都能进入。用 `autoAuth: false` 关闭。
|
|
295
75
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
- `?lanmode=invert` — report the loopback flag as `false` even on localhost. The harness then fails exactly the way it does over the LAN; this is how the plugin is verified.
|
|
299
|
-
- `?lanmode=off` — stand the plugin down entirely, to see the page as it would be without it.
|
|
300
|
-
|
|
301
|
-
On a loopback page the plugin substitutes `true` where the real value is already `true`, so it cannot change behaviour there.
|
|
302
|
-
|
|
303
|
-
## What it is not
|
|
304
|
-
|
|
305
|
-
**Not authentication.** It adds no password and does not widen what the server accepts — the harness answers those same calls with or without it. `direct` mode does make the harness reachable by anyone who can reach that port, exactly as a reverse proxy would. If other people share your network, put a real gate in front of the harness. A plugin cannot do that job: the web server hands plugins their own routes and no way to intercept anyone else's.
|
|
306
|
-
|
|
307
|
-
**No microphone over plain HTTP.** Browsers withhold `navigator.mediaDevices` outside a secure context, so voice input plugins stop working on a plain-HTTP LAN address. Nothing can polyfill that. If you need the microphone, keep HTTPS in front and use `proxy` mode.
|
|
308
|
-
|
|
309
|
-
## Install
|
|
76
|
+
### 安装方法
|
|
310
77
|
|
|
311
78
|
```bash
|
|
312
79
|
dsh plugin --profile web add @goodandready/dsh-lanmode
|
|
313
80
|
```
|
|
314
81
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
## License
|
|
318
|
-
|
|
319
|
-
MIT
|
|
82
|
+
</details>
|
package/lib/bridge.js
CHANGED
|
@@ -20,6 +20,7 @@ import https from 'node:https'
|
|
|
20
20
|
import { forceLoopback, isConnectionBundle } from './loopback-source.js'
|
|
21
21
|
|
|
22
22
|
import { allowed } from './access.js'
|
|
23
|
+
import { handoffLocation, shouldHandoff, tokenFrom } from './handoff.js'
|
|
23
24
|
import { REFUSED, isPrivileged } from './privileged.js'
|
|
24
25
|
|
|
25
26
|
function rewritten(headers, authority) {
|
|
@@ -103,6 +104,18 @@ export function startDirectBridge(ctx, options) {
|
|
|
103
104
|
const refuse = throttle(options.log, 10000)
|
|
104
105
|
const streamTimeoutMs = options.streamTimeoutMs ?? 0
|
|
105
106
|
const unlocked = options.unlockPrivileged !== false
|
|
107
|
+
// Токен спрашиваем у ядра при каждом отказе, а не запоминаем: он меняется
|
|
108
|
+
// при перезагрузке дерева плагинов, и запомненный увёл бы гостя по кругу.
|
|
109
|
+
const currentToken = () => {
|
|
110
|
+
if (options.autoAuth === false) return ''
|
|
111
|
+
try {
|
|
112
|
+
const connection = ctx.get?.('connection')
|
|
113
|
+
if (connection === undefined) return ''
|
|
114
|
+
return tokenFrom(connection.authenticatedUrl('http://' + authority))
|
|
115
|
+
} catch (noService) {
|
|
116
|
+
return ''
|
|
117
|
+
}
|
|
118
|
+
}
|
|
106
119
|
const hosts = options.hosts && options.hosts.length ? options.hosts : ['0.0.0.0']
|
|
107
120
|
|
|
108
121
|
/** Пускать ли этого гостя; отказ пишется в журнал не чаще раза в десять секунд. */
|
|
@@ -145,6 +158,21 @@ export function startDirectBridge(ctx, options) {
|
|
|
145
158
|
timeout: streamTimeoutMs || undefined,
|
|
146
159
|
}, (answer) => {
|
|
147
160
|
answer.setTimeout(streamTimeoutMs)
|
|
161
|
+
const handoff = shouldHandoff({
|
|
162
|
+
method: req.method, url: req.url, status: answer.statusCode, token: currentToken(),
|
|
163
|
+
})
|
|
164
|
+
if (handoff) {
|
|
165
|
+
// Тело отказа гостю не нужно, но выкачать его надо: брошенный ответ
|
|
166
|
+
// держал бы соединение с харнессом открытым.
|
|
167
|
+
answer.resume()
|
|
168
|
+
res.writeHead(303, {
|
|
169
|
+
'cache-control': 'no-store',
|
|
170
|
+
'location': handoffLocation(req.url, currentToken()),
|
|
171
|
+
'referrer-policy': 'no-referrer',
|
|
172
|
+
})
|
|
173
|
+
res.end()
|
|
174
|
+
return
|
|
175
|
+
}
|
|
148
176
|
if (!patching) {
|
|
149
177
|
res.writeHead(answer.statusCode || 502, answer.headers)
|
|
150
178
|
answer.pipe(res)
|
package/lib/handoff.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Передача токена гостю из сети.
|
|
2
|
+
//
|
|
3
|
+
// Токен запуска ядро придумывает заново при каждом старте и держит в памяти
|
|
4
|
+
// процесса. Кука, которую он выдаёт в обмен на токен, привязана к адресу и
|
|
5
|
+
// живёт своим сроком, поэтому после перезапуска харнесса человек с сетевого
|
|
6
|
+
// адреса упирается в «authentication required» и идёт искать новую ссылку в
|
|
7
|
+
// журнале. Ссылку эту ядро печатает для себя, а не для него.
|
|
8
|
+
//
|
|
9
|
+
// Мост стоит ровно посередине и знает обе стороны: он видит отказ харнесса и
|
|
10
|
+
// может спросить у ядра нынешний токен. Поэтому вместо отказа он отправляет
|
|
11
|
+
// гостя по тому же адресу с токеном — дальше ядро само выдаёт куку и убирает
|
|
12
|
+
// токен из адреса.
|
|
13
|
+
//
|
|
14
|
+
// Это НЕ проверка личности: у кого есть доступ к порту, тот и войдёт. Плагин и
|
|
15
|
+
// так пишет об этом при запуске; здесь то же самое становится ещё заметнее.
|
|
16
|
+
|
|
17
|
+
/** Метка попытки: без неё браузер закружится между отказом и подстановкой. */
|
|
18
|
+
export const RETRY_MARK = 'dsh-lan-auth'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Достать токен из адреса, который выдаёт ядро (`authenticatedUrl`).
|
|
22
|
+
*
|
|
23
|
+
* Разбираем адрес, а не строку: в нём может не быть токена вовсе (сборка без
|
|
24
|
+
* проверки), и тогда подставлять нечего.
|
|
25
|
+
*
|
|
26
|
+
* @returns {string} пустая строка, если токена нет
|
|
27
|
+
*/
|
|
28
|
+
export function tokenFrom(url) {
|
|
29
|
+
if (typeof url !== 'string' || url === '') return ''
|
|
30
|
+
try {
|
|
31
|
+
return new URL(url).searchParams.get('token') ?? ''
|
|
32
|
+
} catch (notAnUrl) {
|
|
33
|
+
return ''
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Отправлять ли гостя за токеном.
|
|
39
|
+
*
|
|
40
|
+
* Только страница и только отказ: у запроса за данными свой ответ, и подмена
|
|
41
|
+
* его переходом сломала бы вызывающий код. Повторная попытка отсекается
|
|
42
|
+
* меткой: если и с токеном отказали, значит токен не тот, и ходить по кругу
|
|
43
|
+
* незачем.
|
|
44
|
+
*/
|
|
45
|
+
export function shouldHandoff({ method, url, status, token }) {
|
|
46
|
+
if (status !== 401) return false
|
|
47
|
+
if (method !== 'GET') return false
|
|
48
|
+
if (typeof token !== 'string' || token === '') return false
|
|
49
|
+
const path = pathOf(url)
|
|
50
|
+
if (path.pathname !== '/') return false
|
|
51
|
+
return !path.searchParams.has(RETRY_MARK)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Куда отправить: тот же путь, свой токен и метка попытки.
|
|
56
|
+
*
|
|
57
|
+
* Чужой токен из адреса выкидываем: он уже не подошёл, а два токена подряд
|
|
58
|
+
* ядро считает за подделку и отказывает вовсе.
|
|
59
|
+
*/
|
|
60
|
+
export function handoffLocation(url, token) {
|
|
61
|
+
const at = pathOf(url)
|
|
62
|
+
at.searchParams.delete('token')
|
|
63
|
+
at.searchParams.set('token', token)
|
|
64
|
+
at.searchParams.set(RETRY_MARK, '1')
|
|
65
|
+
return at.pathname + '?' + at.searchParams.toString()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function pathOf(url) {
|
|
69
|
+
return new URL(typeof url === 'string' && url !== '' ? url : '/', 'http://dsh.invalid')
|
|
70
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -260,6 +260,10 @@ async function raiseListener(ctx, config, state) {
|
|
|
260
260
|
if (rules.length === 0) {
|
|
261
261
|
say('список разрешённых адресов пуст. Заполните allow — это не пароль, но круг сузит.')
|
|
262
262
|
}
|
|
263
|
+
if (config.autoAuth !== false) {
|
|
264
|
+
say('токен подставляется гостю сам: после перезапуска харнесса заходить заново не нужно, '
|
|
265
|
+
+ 'но и спросить его у гостя больше некому. Выключается настройкой autoAuth.')
|
|
266
|
+
}
|
|
263
267
|
}
|
|
264
268
|
|
|
265
269
|
state.listener = { scheme: tls ? 'https' : 'http', hosts, port }
|
|
@@ -273,6 +277,7 @@ async function raiseListener(ctx, config, state) {
|
|
|
273
277
|
unlockPrivileged: unlocked,
|
|
274
278
|
privilegedExtra: config.privilegedExtra,
|
|
275
279
|
streamTimeoutMs: config.streamTimeoutMs || 0,
|
|
280
|
+
autoAuth: config.autoAuth !== false,
|
|
276
281
|
})
|
|
277
282
|
}
|
|
278
283
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-lanmode",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.6",
|
|
4
4
|
"description": "LAN and reverse-proxy access for the DeepSeek Harness Web UI: returns the settings service on pages that are not localhost, fills in the Web APIs the browser withholds on plain HTTP, and can open a listener of its own so nothing else is needed. Adapted for DeepSeek Harness 0.1.2-alpha.1.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|