@goodandready/dsh-lanmode 0.6.6 → 0.6.7

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 CHANGED
@@ -1,82 +1,319 @@
1
- # 📦 @goodandready/dsh-lanmode
1
+ # dsh-lanmode
2
2
 
3
- <div align="center">
3
+ > Adapted for DeepSeek Harness **0.1.2-alpha.1**: the host now decides LAN trust from the request `Host` header, so the plugin no longer patches the page for it.
4
4
 
5
- [![npm version](https://img.shields.io/npm/v/@goodandready/dsh-lanmode.svg?style=flat-square)](https://www.npmjs.com/package/@goodandready/dsh-lanmode)
6
- [![license](https://img.shields.io/github/license/GooDAnDReaDY/dsh-lanmode.svg?style=flat-square)](LICENSE)
7
- [![DSH Plugin](https://img.shields.io/badge/DSH-Plugin-6366f1.svg?style=flat-square)](https://github.com/topics/dsh-plugin)
8
5
 
9
- **[ 🇬🇧 English ](#-english) [ 🇷🇺 Русский ](#-русский) [ 🇨🇳 中文 ](#-中文)**
6
+ Open the [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) Web UI from another device a phone, a tablet, the laptop on the other side of the room — and have **all of it** work, including the parts the UI switches off when the page is not `localhost`.
10
7
 
11
- </div>
8
+ Works whether you put a reverse proxy in front of the harness or let this plugin serve the network itself. Pick a mode, restart, done.
12
9
 
13
- ---
10
+ ## What breaks without it
14
11
 
15
- <a name="-english"></a>
16
- ## 🇬🇧 English
12
+ Reach the UI at a LAN address and you get some mix of:
17
13
 
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.
14
+ - **Settings Models**: `settings are unavailable in this browser`
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
19
18
 
20
- ### Features
19
+ None of that is the server refusing. The server serves settings over the network perfectly well.
21
20
 
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`.
21
+ ## Why it happens
28
22
 
29
- ### Install
23
+ Two independent things.
30
24
 
31
- ```bash
32
- dsh plugin --profile web add @goodandready/dsh-lanmode
25
+ **The settings service turns itself off.** The UI decides from the page's hostname:
26
+
27
+ ```js
28
+ isLoopback: pageLocation === undefined || isLoopbackHostname(hostname)
33
29
  ```
34
30
 
35
- ---
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.
36
32
 
37
- <a name="-русский"></a>
38
- <details open>
39
- <summary><h2>🇷🇺 Русский (Полное руководство)</h2></summary>
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.
40
34
 
41
- Вспомогательный плагин для доступа по локальной сети и поддержка браузерных медиа-API в DeepSeek Harness: обеспечивает работу с мобильных устройств и предоставляет полифиллы для HTTP-окружения.
35
+ ## What the plugin does
42
36
 
43
- ### Возможности
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.
44
38
 
45
- - **Доступ по локальной сети**: вход в Web UI с телефонов и планшетов в подсетях `192.168.x.x` / `10.x.x.x`.
46
- - **Полифиллы медиа-API**: обход ограничений браузера на работу микрофона и диктовки без HTTPS в локальной сети.
47
- - **Совместимость с прокси**: прозрачная работа за Nginx, Traefik и Caddy.
48
- - **Вход из сети без токена**: после перезапуска харнесса мост сам подставляет гостю
49
- нынешний токен запуска, и новую ссылку искать не нужно. Это не проверка личности:
50
- кто дотянулся до порта, тот и вошёл. Выключается настройкой `autoAuth: false`.
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. |
51
44
 
52
- ### Установка
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.
53
46
 
54
- ```bash
55
- dsh plugin --profile web add @goodandready/dsh-lanmode
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
56
132
  ```
57
133
 
58
- </details>
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.
59
137
 
60
- ---
138
+ ## Replacing a reverse proxy
61
139
 
62
- <a name="-中文"></a>
63
- <details>
64
- <summary><h2>🇨🇳 中文 (完整技术文档)</h2></summary>
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.
65
144
 
66
- DeepSeek Harness 局域网访问优化与 HTTP 媒体接口兼容插件:支持内网多端接入与非 HTTPS 媒体接口 Polyfill。
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
+ ```
67
160
 
68
- ### 核心亮点
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
+ ```
69
180
 
70
- - **局域网全端接入**:支持移动设备通过 `192.168.x.x` 等内网网段顺畅访问。
71
- - **媒体接口 Polyfill**:解除纯 HTTP 环境下浏览器录音与语音 API 的安全阻断。
72
- - **反向代理完美适配**:兼容 Nginx、Traefik、Caddy 等反向代理方案。
73
- - **局域网免令牌进入**:Harness 重启后,网桥会自行把当前启动令牌交给访客,无需再去找新链接。
74
- 这不是身份校验:能连到该端口的人都能进入。用 `autoAuth: false` 关闭。
181
+ The browser asks once about the certificate; compare the fingerprint printed in
182
+ the log and accept it.
75
183
 
76
- ### 安装方法
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
210
+ ```
211
+
212
+ Addresses and CIDR ranges, IPv4 and IPv6. An empty list means everyone, which is
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.
215
+
216
+ Two honest limits. This is not authentication: whoever is on the list gets in
217
+ unchecked. And behind a reverse proxy it means nothing — every request arrives
218
+ from the proxy, so filter there instead.
219
+
220
+ ## The price of it working
221
+
222
+ The harness pins its privileged calls — settings, credentials, agent presets,
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.
228
+
229
+ The price, stated plainly: **any device that reaches this port can read and
230
+ change your API keys, with no authentication at all.** Nothing here asks who you
231
+ are.
232
+
233
+ It is a setting, not a secret:
234
+
235
+ ```yaml
236
+ unlockPrivileged: false # settings over the network stop working
237
+ ```
238
+
239
+ Off, the privileged calls are refused by the bridge with a message saying why,
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
262
+
263
+ The plugin holds on to the harness's internals: the index tap, the name of the
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.
268
+
269
+ So at startup it checks its own assumptions and says what it found: one line
270
+ when everything is in place, a loud complaint naming what moved when it is not.
271
+ The same list is on the diagnostics page.
272
+
273
+ ## Settings
274
+
275
+ All of it can be edited as the `dsh-lanmode` namespace — in `$DSH_HOME/settings.yaml`, or from the UI once the settings pages work.
276
+
277
+ | Setting | Default | Meaning |
278
+ |---|---|---|
279
+ | `mode` | `proxy` | `proxy`, `direct` or `auto` |
280
+ | `directHost` | `0.0.0.0` | `direct`: which address to listen on |
281
+ | `directPort` | `3088` | `direct`: which port to listen on |
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 |
295
+
296
+ ## Checking it
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
77
310
 
78
311
  ```bash
79
312
  dsh plugin --profile web add @goodandready/dsh-lanmode
80
313
  ```
81
314
 
82
- </details>
315
+ Restart the harness, then reload the browser.
316
+
317
+ ## License
318
+
319
+ MIT
package/lib/bridge.js CHANGED
@@ -20,7 +20,6 @@ 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'
24
23
  import { REFUSED, isPrivileged } from './privileged.js'
25
24
 
26
25
  function rewritten(headers, authority) {
@@ -104,18 +103,6 @@ export function startDirectBridge(ctx, options) {
104
103
  const refuse = throttle(options.log, 10000)
105
104
  const streamTimeoutMs = options.streamTimeoutMs ?? 0
106
105
  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
- }
119
106
  const hosts = options.hosts && options.hosts.length ? options.hosts : ['0.0.0.0']
120
107
 
121
108
  /** Пускать ли этого гостя; отказ пишется в журнал не чаще раза в десять секунд. */
@@ -158,21 +145,6 @@ export function startDirectBridge(ctx, options) {
158
145
  timeout: streamTimeoutMs || undefined,
159
146
  }, (answer) => {
160
147
  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
- }
176
148
  if (!patching) {
177
149
  res.writeHead(answer.statusCode || 502, answer.headers)
178
150
  answer.pipe(res)
@@ -242,6 +214,24 @@ export function startDirectBridge(ctx, options) {
242
214
  socket.on('error', drop)
243
215
  socket.on('close', drop)
244
216
  })
217
+ // Харнесс может отказать подъёму обычным ответом — например, потребовать
218
+ // токен и вернуть 401. Раньше этот случай не обрабатывался вовсе: мост
219
+ // ждал только «101» и «сеть отвалилась», а обычный ответ проглатывал.
220
+ // Браузер при этом не получал ничего и ждал бесконечно. Поток событий не
221
+ // поднимался, и по сети пропадали и список бесед, и ответы агента — при
222
+ // живой странице и работающем харнессе.
223
+ upstream.on('response', (answer) => {
224
+ const lines = ['HTTP/1.1 ' + answer.statusCode + ' ' + (answer.statusMessage || '')]
225
+ for (const [key, value] of Object.entries(answer.headers)) lines.push(key + ': ' + value)
226
+ lines.push('connection: close')
227
+ try {
228
+ socket.write(lines.join('\r\n') + '\r\n\r\n')
229
+ answer.pipe(socket)
230
+ } catch (already) {
231
+ try { socket.destroy() } catch (dead) { /* уже мертво */ }
232
+ }
233
+ })
234
+
245
235
  upstream.on('error', () => { try { socket.destroy() } catch (already) { /* уже мертво */ } })
246
236
  // head сюда не пишем: это байты уже установленного соединения, а не тело
247
237
  // запроса. Их место — в upstreamSocket, сразу после рукопожатия.
package/lib/index.js CHANGED
@@ -260,10 +260,6 @@ 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
- }
267
263
  }
268
264
 
269
265
  state.listener = { scheme: tls ? 'https' : 'http', hosts, port }
@@ -277,7 +273,6 @@ async function raiseListener(ctx, config, state) {
277
273
  unlockPrivileged: unlocked,
278
274
  privilegedExtra: config.privilegedExtra,
279
275
  streamTimeoutMs: config.streamTimeoutMs || 0,
280
- autoAuth: config.autoAuth !== false,
281
276
  })
282
277
  }
283
278
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-lanmode",
3
- "version": "0.6.6",
3
+ "version": "0.6.7",
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",
package/lib/handoff.js DELETED
@@ -1,70 +0,0 @@
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
- }