dsh-embedded-browser-next 0.0.0-stage → 1.0.0

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/lib/routes.js ADDED
@@ -0,0 +1,446 @@
1
+ /**
2
+ * HTTP and WebSocket routes the DSH Web UI talks to.
3
+ *
4
+ * Everything mounts on the DSH host webserver's own origin, and every route runs
5
+ * the same guard the Web UI itself uses (`connection.requestRejection`): the
6
+ * browser panel is exactly as reachable — and exactly as protected — as the GUI
7
+ * it lives in. No extra port, no separate token, no tunnel.
8
+ *
9
+ * Every route carries a **session id**: the HTTP layer cannot infer which
10
+ * conversation a request belongs to, so the panel sends its own. `GET /state`,
11
+ * `GET /sessions` and the `/stream` upgrade take it as a query parameter; the
12
+ * small POST endpoints accept it in the body.
13
+ *
14
+ * @module dsh-embedded-browser/routes
15
+ */
16
+
17
+ import { appendFileSync, statSync, writeFileSync } from 'node:fs'
18
+ import { logFile } from './diagnostics.js'
19
+ import { systemOpen } from './external.js'
20
+
21
+ /** Base path of every route this plugin owns. */
22
+ export const BASE_PATH = '/api/dsh-embedded-browser'
23
+
24
+ /** Maximum accepted JSON body for the small control endpoints. */
25
+ const MAX_BODY_BYTES = 64 * 1024
26
+
27
+ /** Write a JSON response. */
28
+ export function writeJson(res, status, value) {
29
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
30
+ res.end(JSON.stringify(value))
31
+ }
32
+
33
+ /**
34
+ * Read a small JSON request body.
35
+ *
36
+ * A body that is too large or not JSON is the **caller's** mistake, so it carries
37
+ * its own status and must not surface as a 500: a 500 means the host broke, gets
38
+ * logged as a fault, and hides the real reason from the panel.
39
+ */
40
+ async function readJson(req) {
41
+ const chunks = []
42
+ let size = 0
43
+ for await (const chunk of req) {
44
+ size += chunk.length
45
+ if (size > MAX_BODY_BYTES) {
46
+ const error = new Error(`request body exceeds ${MAX_BODY_BYTES} bytes`)
47
+ error.status = 413
48
+ throw error
49
+ }
50
+ chunks.push(chunk)
51
+ }
52
+ if (size === 0) return {}
53
+ try {
54
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
55
+ } catch {
56
+ const error = new Error('request body is not valid JSON')
57
+ error.status = 400
58
+ throw error
59
+ }
60
+ }
61
+
62
+ /** Answer a failed handler with the status the error asked for (500 by default). */
63
+ function writeError(res, error) {
64
+ writeJson(res, error?.status ?? 500, { error: error?.message ?? String(error) })
65
+ }
66
+
67
+ /** Read one query parameter from a route path. */
68
+ function queryParam(req, name) {
69
+ const raw = req.url ?? ''
70
+ const index = raw.indexOf('?')
71
+ if (index < 0) return undefined
72
+ const params = new URLSearchParams(raw.slice(index + 1))
73
+ const value = params.get(name)
74
+ return value === null || value === '' ? undefined : value
75
+ }
76
+
77
+ /**
78
+ * Reject an unauthenticated request with the same codes the GUI uses.
79
+ *
80
+ * The `connection` service object is passed in rather than read from `ctx`:
81
+ * Cordis forbids reaching a service through the context proxy unless the plugin
82
+ * declared it in `inject`, and this plugin keeps web services optional.
83
+ */
84
+ /**
85
+ * [diagnostics] Append one line to the panel trace file.
86
+ *
87
+ * The panel speaks to this host on the GUI's own origin, so its failures are
88
+ * invisible from outside: a rejected upgrade and a client that never dialled look
89
+ * identical (no panel attached). This records what actually arrived so it can be
90
+ * read from the filesystem. `DSH_BROWSER_TRACE` relocates the file; `off` disables.
91
+ */
92
+ const TRACE_FILE = logFile('panel-trace.log', 'DSH_BROWSER_TRACE')
93
+ const TRACE_MAX_BYTES = 512 * 1024
94
+ function trace(line) {
95
+ if (TRACE_FILE === '') return
96
+ try {
97
+ // Kept enabled on purpose so a future failure can be diagnosed without a
98
+ // rebuild; the size cap keeps that from becoming its own problem.
99
+ if ((statSync(TRACE_FILE, { throwIfNoEntry: false })?.size ?? 0) > TRACE_MAX_BYTES) {
100
+ writeFileSync(TRACE_FILE, `${new Date().toISOString()} trace rotated\n`)
101
+ }
102
+ appendFileSync(TRACE_FILE, `${new Date().toISOString()} ${line}\n`)
103
+ } catch {
104
+ /* diagnostics must never affect a request */
105
+ }
106
+ }
107
+
108
+ /**
109
+ * [dsh-rc5 fix] The Host's own HTTP origin, proved by the request that just arrived.
110
+ *
111
+ * The panel cannot trust `location` for this: the desktop shell serves the page from
112
+ * `dsh-app://app/`, so `location.host` is the literal string `app`, and a `ws://app/...`
113
+ * dial closes with code 1006 and never appears in any host log. Hard-coding a single
114
+ * source is what made this flip with every shell change, so every state response now
115
+ * advertises the origin the caller already reached, and the client dials there.
116
+ */
117
+ function originOf(req) {
118
+ const host = req.headers?.host
119
+ if (typeof host !== 'string' || host === '') return undefined
120
+ const forwarded = req.headers?.['x-forwarded-proto']
121
+ const secure = typeof forwarded === 'string' && forwarded.split(',')[0].trim() === 'https'
122
+ return `${secure ? 'https' : 'http'}://${host}`
123
+ }
124
+
125
+ function rejected(connection, req, res) {
126
+ const rejection = connection.requestRejection(req)
127
+ if (rejection === undefined) return false
128
+ trace(
129
+ `REJECT ${rejection} ${req.method ?? 'GET'} ${req.url ?? ''} host=${req.headers?.host ?? '-'} ` +
130
+ `origin=${req.headers?.origin ?? '-'} cookie=${req.headers?.cookie ? 'yes' : 'no'}`,
131
+ )
132
+ res.writeHead(rejection, { 'content-type': 'text/plain; charset=utf-8' })
133
+ res.end(rejection === 401 ? 'unauthorized' : 'forbidden')
134
+ return true
135
+ }
136
+
137
+ /**
138
+ * Build the plugin's plain HTTP routes.
139
+ *
140
+ * @param deps - context, browser manager, human broker, screencast hub.
141
+ * @returns webserver route objects (registered by the caller inside an effect).
142
+ */
143
+ export function makeRoutes({ connection, manager, human, hub, version, applySettings, restorePanel, openWindow, openExternal = systemOpen }) {
144
+ /** Browser-level state, plus one session's own page when a session is given. */
145
+ const stateFor = async (sessionId) => {
146
+ const status = await manager.status(sessionId)
147
+ const stream = sessionId === undefined
148
+ ? undefined
149
+ : hub.watched === sessionId ? 'screencast' : hub.pollers.has(sessionId) ? 'poll' : 'idle'
150
+ return {
151
+ ...status,
152
+ version,
153
+ sessionId: sessionId ?? null,
154
+ stream: stream ?? null,
155
+ human: human.snapshot(sessionId) ?? null,
156
+ panels: sessionId === undefined ? hub.connections.size : hub.connectionsFor(sessionId).length,
157
+ framesDropped: hub.framesDropped,
158
+ }
159
+ }
160
+
161
+ return [
162
+ {
163
+ kind: 'exact',
164
+ path: `${BASE_PATH}/debug`,
165
+ handler: (req, res) => {
166
+ if (rejected(connection, req, res)) return
167
+ trace(`CLIENT ${req.url ?? ''}`)
168
+ writeJson(res, 200, { ok: true })
169
+ },
170
+ },
171
+ {
172
+ kind: 'exact',
173
+ path: `${BASE_PATH}/state`,
174
+ handler: async (req, res) => {
175
+ if (rejected(connection, req, res)) return
176
+ if ((req.method ?? 'GET') !== 'GET') return writeJson(res, 405, { error: 'method not allowed' })
177
+ try {
178
+ writeJson(res, 200, { ...(await stateFor(queryParam(req, 'session'))), streamBaseUrl: originOf(req) })
179
+ } catch (error) {
180
+ writeError(res, error)
181
+ }
182
+ },
183
+ },
184
+ {
185
+ kind: 'exact',
186
+ path: `${BASE_PATH}/mjpeg`,
187
+ handler: async (req, res) => {
188
+ if (rejected(connection, req, res)) return
189
+ if ((req.method ?? 'GET') !== 'GET') return writeJson(res, 405, { error: 'method not allowed' })
190
+ const sessionId = queryParam(req, 'session')
191
+ if (sessionId === undefined) return writeJson(res, 400, { error: 'session is required' })
192
+ // This response stays open for the life of the panel, so nothing here may
193
+ // write a JSON body or wait for it: a replacement stream owns the socket
194
+ // until the viewer goes away.
195
+ trace(`MJPEG open sid=${sessionId} sid4=${sessionId.slice(-4)} ua=${(req.headers?.['user-agent'] ?? '-').slice(0, 40)}`)
196
+ try {
197
+ await hub.attachMjpeg(sessionId, res)
198
+ } catch (error) {
199
+ trace(`MJPEG attach failed: ${error.message}`)
200
+ try {
201
+ res.destroy()
202
+ } catch {
203
+ /* already gone */
204
+ }
205
+ }
206
+ },
207
+ },
208
+ {
209
+ kind: 'exact',
210
+ path: `${BASE_PATH}/sessions`,
211
+ handler: async (req, res) => {
212
+ if (rejected(connection, req, res)) return
213
+ if ((req.method ?? 'GET') !== 'GET') return writeJson(res, 405, { error: 'method not allowed' })
214
+ try {
215
+ const browser = await manager.status()
216
+ writeJson(res, 200, {
217
+ version,
218
+ running: browser.running,
219
+ mode: browser.mode,
220
+ streamBaseUrl: originOf(req),
221
+ sessions: manager.listSessions(),
222
+ pending: human.snapshotAll(),
223
+ watched: hub.watched ?? null,
224
+ })
225
+ } catch (error) {
226
+ writeError(res, error)
227
+ }
228
+ },
229
+ },
230
+ {
231
+ kind: 'exact',
232
+ path: `${BASE_PATH}/open`,
233
+ handler: async (req, res) => {
234
+ if (rejected(connection, req, res)) return
235
+ if (req.method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
236
+ try {
237
+ const body = await readJson(req)
238
+ const sessionId = body.sessionId ?? queryParam(req, 'session')
239
+ if (typeof sessionId !== 'string' || sessionId === '') return writeJson(res, 400, { error: 'sessionId is required' })
240
+ await manager.ensureSession(sessionId, { label: body.label })
241
+ await hub.pushState({ force: true })
242
+ writeJson(res, 200, await stateFor(sessionId))
243
+ } catch (error) {
244
+ writeError(res, error)
245
+ }
246
+ },
247
+ },
248
+ {
249
+ kind: 'exact',
250
+ path: `${BASE_PATH}/close`,
251
+ handler: async (req, res) => {
252
+ if (rejected(connection, req, res)) return
253
+ if (req.method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
254
+ try {
255
+ const body = await readJson(req)
256
+ const sessionId = body.sessionId ?? queryParam(req, 'session')
257
+ if (typeof sessionId !== 'string' || sessionId === '') return writeJson(res, 400, { error: 'sessionId is required' })
258
+ human.cancel(sessionId, 'session closed from the panel')
259
+ const closed = await manager.closeSession(sessionId, { reason: 'closed from the panel' })
260
+ await hub.sync()
261
+ await hub.pushState({ force: true })
262
+ writeJson(res, 200, { ok: closed, sessionId })
263
+ } catch (error) {
264
+ writeError(res, error)
265
+ }
266
+ },
267
+ },
268
+ {
269
+ kind: 'exact',
270
+ path: `${BASE_PATH}/human-done`,
271
+ handler: async (req, res) => {
272
+ if (rejected(connection, req, res)) return
273
+ if (req.method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
274
+ try {
275
+ const body = await readJson(req)
276
+ const settled = human.done(body.id, body.text !== undefined ? { reply: String(body.text) } : {})
277
+ await hub.pushState({ force: true })
278
+ writeJson(res, settled ? 200 : 409, { ok: settled })
279
+ } catch (error) {
280
+ writeJson(res, 400, { error: error.message })
281
+ }
282
+ },
283
+ },
284
+ {
285
+ kind: 'exact',
286
+ path: `${BASE_PATH}/settings`,
287
+ handler: async (req, res) => {
288
+ if (rejected(connection, req, res)) return
289
+ const method = req.method ?? 'GET'
290
+ try {
291
+ if (method === 'GET') {
292
+ // One description, built by the same function that applies changes:
293
+ // an empty patch reads the settings in force without writing anything.
294
+ writeJson(res, 200, typeof applySettings === 'function' ? applySettings({}) : hub.residency.describe())
295
+ return
296
+ }
297
+ if (method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
298
+ const body = await readJson(req)
299
+ // Validate here rather than trusting the panel: a mode this build does
300
+ // not know would otherwise be persisted and silently ignored forever.
301
+ const patch = {}
302
+ if (body.mode !== undefined) {
303
+ if (!['always', 'on-demand', 'off'].includes(body.mode)) return writeJson(res, 400, { error: 'unknown mode' })
304
+ patch.realBrowser = body.mode
305
+ }
306
+ if (body.idleMinutes !== undefined) {
307
+ const minutes = Number(body.idleMinutes)
308
+ if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) return writeJson(res, 400, { error: 'idleMinutes out of range' })
309
+ patch.reclaimIdleMinutes = minutes
310
+ }
311
+ if (body.maxLive !== undefined) {
312
+ const max = Number(body.maxLive)
313
+ if (!Number.isFinite(max) || max < 0 || max > 64) return writeJson(res, 400, { error: 'maxLive out of range' })
314
+ patch.maxLiveBrowsers = max
315
+ }
316
+ if (body.idleShutdownMinutes !== undefined) {
317
+ const minutes = Number(body.idleShutdownMinutes)
318
+ if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) {
319
+ return writeJson(res, 400, { error: 'idleShutdownMinutes out of range' })
320
+ }
321
+ patch.idleShutdownMinutes = minutes
322
+ }
323
+ const applied = typeof applySettings === 'function' ? applySettings(patch) : hub.residency.describe()
324
+ await hub.pushState({ force: true })
325
+ writeJson(res, 200, applied)
326
+ } catch (error) {
327
+ writeError(res, error)
328
+ }
329
+ },
330
+ },
331
+ {
332
+ kind: 'exact',
333
+ path: `${BASE_PATH}/open-external`,
334
+ handler: async (req, res) => {
335
+ if (rejected(connection, req, res)) return
336
+ if (req.method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
337
+ try {
338
+ const body = await readJson(req)
339
+ const opened = await openExternal(body.url ?? queryParam(req, 'url'))
340
+ writeJson(res, 200, { ok: true, url: String(opened) })
341
+ } catch (error) {
342
+ writeError(res, error)
343
+ }
344
+ },
345
+ },
346
+ {
347
+ kind: 'exact',
348
+ path: `${BASE_PATH}/open-window`,
349
+ handler: async (req, res) => {
350
+ if (rejected(connection, req, res)) return
351
+ if (req.method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
352
+ try {
353
+ const body = await readJson(req)
354
+ const sessionId = String(body.sessionId ?? queryParam(req, 'sessionId') ?? '')
355
+ if (sessionId === '') throw new Error('open-window needs a sessionId')
356
+ // The router — not the bare manager — owns the window: it marks the
357
+ // session windowed, pushes that state to the panel *before* anything
358
+ // waits on the guest, and asks the panel to let go of its copy. Calling
359
+ // `manager.openWindow` straight from here was how the panel's own
360
+ // 「独立窗口」 button ended up with a real window it did not know about:
361
+ // `windowed` stayed empty, the panel kept its guest and kept winning
362
+ // routing, and 「浮窗」 then floated the panel copy while the window
363
+ // stayed on screen (measured 2026-11-29).
364
+ if (typeof openWindow !== 'function') throw new Error('open-window is not wired in this deployment')
365
+ writeJson(res, 200, await openWindow(sessionId, { url: body.url }))
366
+ } catch (error) {
367
+ writeError(res, error)
368
+ }
369
+ },
370
+ },
371
+ {
372
+ kind: 'exact',
373
+ path: `${BASE_PATH}/restore-panel`,
374
+ handler: async (req, res) => {
375
+ if (rejected(connection, req, res)) return
376
+ if (req.method !== 'POST') return writeJson(res, 405, { error: 'method not allowed' })
377
+ try {
378
+ const body = await readJson(req)
379
+ const sessionId = String(body.sessionId ?? queryParam(req, 'sessionId') ?? '')
380
+ if (sessionId === '') throw new Error('restore-panel needs a sessionId')
381
+ if (typeof restorePanel !== 'function') throw new Error('restore-panel is not wired in this deployment')
382
+ writeJson(res, 200, await restorePanel(sessionId))
383
+ } catch (error) {
384
+ writeError(res, error)
385
+ }
386
+ },
387
+ },
388
+ {
389
+ kind: 'exact',
390
+ path: `${BASE_PATH}/health`,
391
+ handler: async (req, res) => {
392
+ if (rejected(connection, req, res)) return
393
+ const status = await manager.status()
394
+ writeJson(res, 200, {
395
+ ok: true,
396
+ version,
397
+ executable: manager.executable,
398
+ mode: manager.mode,
399
+ running: status.running,
400
+ sessions: status.sessions,
401
+ profileDir: manager.profileDir(),
402
+ })
403
+ },
404
+ },
405
+ ]
406
+ }
407
+
408
+ /**
409
+ * Build the screencast/input upgrade route.
410
+ *
411
+ * @param deps - context and screencast hub.
412
+ * @returns an upgrade route object, or undefined when the optional `ws` acceptance fails.
413
+ */
414
+ export function makeUpgradeRoute({ connection, hub }) {
415
+ return {
416
+ path: `${BASE_PATH}/stream`,
417
+ handler: (req, socket) => {
418
+ const rejection = connection.requestRejection(req)
419
+ trace(
420
+ `UPGRADE ${rejection === undefined ? 'allow' : `deny-${rejection}`} ${req.url ?? ''} ` +
421
+ `origin=${req.headers?.origin ?? '-'} cookie=${req.headers?.cookie ? 'yes' : 'no'}`,
422
+ )
423
+ if (rejection !== undefined) {
424
+ socket.write(
425
+ `HTTP/1.1 ${rejection} ${rejection === 401 ? 'Unauthorized' : 'Forbidden'}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`,
426
+ )
427
+ socket.destroy()
428
+ return
429
+ }
430
+ const sessionId = queryParam(req, 'session')
431
+ if (sessionId === undefined) {
432
+ socket.write('HTTP/1.1 400 Bad Request\r\nconnection: close\r\ncontent-length: 0\r\n\r\n')
433
+ socket.destroy()
434
+ return
435
+ }
436
+ // Imported lazily so a broken upgrade never affects plugin load.
437
+ import('./ws.js')
438
+ .then(({ acceptUpgrade }) => {
439
+ acceptUpgrade(req, socket, undefined, (clientConnection) => {
440
+ void hub.attach(clientConnection, sessionId)
441
+ })
442
+ })
443
+ .catch(() => socket.destroy())
444
+ },
445
+ }
446
+ }