dsh-shared-browser 0.0.0-stage → 0.6.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/bridge.mjs ADDED
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Host-side hub for the shared browser.
3
+ *
4
+ * The browser UI (a Client plugin) owns the Electron <webview>. The Host owns
5
+ * the tool surface. They meet here:
6
+ *
7
+ * Host --SSE /events--> Client (commands: navigate, click, screenshot…)
8
+ * Host <--POST /report-- Client (results, tab list, console, comments)
9
+ *
10
+ * Nothing in this file knows about DSH internals; index.js wires it to routes
11
+ * and tools. One Client instance is attached at a time (the newest stream wins,
12
+ * so a reloaded window never leaves a dead stream behind).
13
+ * @module dsh-shared-browser/lib/bridge
14
+ */
15
+
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ /** Absolute prefix of every route this bundle registers. */
19
+ export const ROUTE_BASE = '/dsh-shared-browser'
20
+
21
+ const KEEPALIVE_MS = 15000
22
+ const DEFAULT_TIMEOUT_MS = 20000
23
+ const MAX_CONSOLE = 2000
24
+ const MAX_NETWORK = 600
25
+ const MAX_COMMENTS = 1000
26
+
27
+ /** Console levels the page can report, most severe first. */
28
+ export const CONSOLE_LEVELS = ['error', 'warning', 'info', 'debug', 'verbose']
29
+
30
+ /** Trim an array to its newest `limit` entries, in place. */
31
+ function trim(list, limit) {
32
+ if (list.length > limit) list.splice(0, list.length - limit)
33
+ }
34
+
35
+ /** One error the caller can present verbatim. */
36
+ export class BridgeError extends Error {
37
+ /** @param {string} message - user-facing sentence. @param {string} [code] - machine tag. */
38
+ constructor(message, code = 'unavailable') {
39
+ super(message)
40
+ this.name = 'BridgeError'
41
+ this.code = code
42
+ }
43
+ }
44
+
45
+ /** Command router between the Host tools and the Client browser UI. */
46
+ export class Hub {
47
+ /** @param {{ attachmentsDir?: string }} [options] - where screenshots land. */
48
+ constructor(options = {}) {
49
+ /** @type {{ id: string, res: import('node:http').ServerResponse, sessionId: string | null, since: number } | null} */
50
+ this.stream = null
51
+ /** @type {Array<Record<string, unknown>>} */
52
+ this.tabs = []
53
+ /** @type {string | null} */
54
+ this.activeTabId = null
55
+ /** @type {Array<Record<string, unknown>>} */
56
+ this.consoleLog = []
57
+ /** @type {Array<Record<string, unknown>>} */
58
+ this.networkLog = []
59
+ /** @type {Array<Record<string, unknown>>} */
60
+ this.comments = []
61
+ /** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void, timer: NodeJS.Timeout }>} */
62
+ this.pending = new Map()
63
+ /** @type {number} */
64
+ this.lastSeen = 0
65
+ /** @type {string | null} */
66
+ this.lastTabKey = null
67
+ /** @type {string} */
68
+ this.attachmentsDir = options.attachmentsDir ?? ''
69
+ /** @type {string | null} */
70
+ this.version = null
71
+ }
72
+
73
+ /** Whether a Client UI is currently streaming to this Host. @returns {boolean} */
74
+ get connected() {
75
+ return this.stream !== null
76
+ }
77
+
78
+ /**
79
+ * Attach the newest SSE stream, dropping any previous one.
80
+ * @param {import('node:http').ServerResponse} res - long-lived response.
81
+ * @param {{ sessionId?: string | null, version?: string | null }} [meta] - client identity.
82
+ */
83
+ attach(res, meta = {}) {
84
+ if (this.stream !== null) {
85
+ try { this.stream.res.end() } catch { /* the old stream is already gone */ }
86
+ }
87
+ res.writeHead(200, {
88
+ 'content-type': 'text/event-stream; charset=utf-8',
89
+ 'cache-control': 'no-store',
90
+ connection: 'keep-alive',
91
+ 'x-accel-buffering': 'no',
92
+ })
93
+ res.write(': connected\n\n')
94
+ const stream = { id: randomUUID(), res, sessionId: meta.sessionId ?? null, since: Date.now() }
95
+ this.stream = stream
96
+ this.lastSeen = Date.now()
97
+ if (typeof meta.version === 'string') this.version = meta.version
98
+ const keepalive = setInterval(() => {
99
+ if (this.stream !== stream) return clearInterval(keepalive)
100
+ try { res.write(': ping\n\n') } catch { /* dropped below */ }
101
+ }, KEEPALIVE_MS)
102
+ res.on('close', () => {
103
+ clearInterval(keepalive)
104
+ if (this.stream === stream) this.stream = null
105
+ this.failAll(new BridgeError('浏览器页签已关闭或页面已刷新,命令已中止。', 'detached'))
106
+ })
107
+ res.on('error', () => { try { res.destroy() } catch { /* already closed */ } })
108
+ }
109
+
110
+ /** Drop the current stream (used on Host shutdown). */
111
+ detach() {
112
+ if (this.stream === null) return
113
+ try { this.stream.res.end() } catch { /* already closed */ }
114
+ this.stream = null
115
+ this.failAll(new BridgeError('浏览器桥已断开。', 'detached'))
116
+ }
117
+
118
+ /**
119
+ * Send one event to the attached Client.
120
+ * @param {string} event - SSE event name.
121
+ * @param {unknown} payload - JSON payload.
122
+ * @returns {boolean} whether it reached a live stream.
123
+ */
124
+ emit(event, payload) {
125
+ if (this.stream === null) return false
126
+ try {
127
+ this.stream.res.write(`event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`)
128
+ return true
129
+ } catch {
130
+ this.stream = null
131
+ return false
132
+ }
133
+ }
134
+
135
+ /** Reject every in-flight command. @param {Error} error - reason. */
136
+ failAll(error) {
137
+ for (const [, entry] of this.pending) {
138
+ clearTimeout(entry.timer)
139
+ entry.reject(error)
140
+ }
141
+ this.pending.clear()
142
+ }
143
+
144
+ /**
145
+ * Run one operation in the Client and await its result.
146
+ * @param {string} op - operation name understood by the Client.
147
+ * @param {Record<string, unknown>} [args] - operation arguments.
148
+ * @param {{ timeoutMs?: number, tabId?: string | null }} [options] - command options.
149
+ * @returns {Promise<unknown>} the Client's result value.
150
+ */
151
+ command(op, args = {}, options = {}) {
152
+ if (this.stream === null) {
153
+ return Promise.reject(new BridgeError(
154
+ '浏览器页签没有连接。先让用户在右侧栏打开 Browser 页签(或调用 bb_open),再执行该操作。',
155
+ 'not-connected',
156
+ ))
157
+ }
158
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
159
+ const id = randomUUID()
160
+ const target = options.tabId ?? this.activeTabId
161
+ const payload = { id, op, args, tabId: target, sentAt: Date.now() }
162
+ return new Promise((resolve, reject) => {
163
+ const timer = setTimeout(() => {
164
+ this.pending.delete(id)
165
+ reject(new BridgeError(`浏览器命令 ${op} 超时(${timeoutMs}ms 未返回)。`, 'timeout'))
166
+ }, timeoutMs)
167
+ this.pending.set(id, { resolve, reject, timer })
168
+ if (!this.emit('command', payload)) {
169
+ clearTimeout(timer)
170
+ this.pending.delete(id)
171
+ reject(new BridgeError('浏览器页签没有连接。', 'not-connected'))
172
+ }
173
+ })
174
+ }
175
+
176
+ /**
177
+ * Ingest one POST /report body from the Client.
178
+ * @param {Record<string, any>} body - report payload.
179
+ * @returns {{ ok: true, notice?: string }} acknowledgement.
180
+ */
181
+ ingest(body) {
182
+ this.lastSeen = Date.now()
183
+ switch (body?.type) {
184
+ case 'result': {
185
+ const entry = this.pending.get(body.id)
186
+ if (entry === undefined) return { ok: true }
187
+ this.pending.delete(body.id)
188
+ clearTimeout(entry.timer)
189
+ if (body.ok) entry.resolve(body.value)
190
+ else entry.reject(new BridgeError(String(body.error ?? '浏览器操作失败。'), 'client-error'))
191
+ return { ok: true }
192
+ }
193
+ case 'tabs': {
194
+ this.tabs = Array.isArray(body.tabs) ? body.tabs.slice(0, 50) : []
195
+ this.activeTabId = typeof body.activeTabId === 'string' ? body.activeTabId : null
196
+ return { ok: true }
197
+ }
198
+ case 'console': {
199
+ const entries = Array.isArray(body.entries) ? body.entries : []
200
+ this.consoleLog.push(...entries)
201
+ trim(this.consoleLog, MAX_CONSOLE)
202
+ return { ok: true }
203
+ }
204
+ case 'network': {
205
+ const entries = Array.isArray(body.entries) ? body.entries : []
206
+ this.networkLog.push(...entries)
207
+ trim(this.networkLog, MAX_NETWORK)
208
+ return { ok: true }
209
+ }
210
+ case 'comment': {
211
+ if (typeof body.comment?.id !== 'string') return { ok: false, notice: 'comment needs an id' }
212
+ this.comments = this.comments.filter(entry => entry.id !== body.comment.id)
213
+ this.comments.push(body.comment)
214
+ trim(this.comments, MAX_COMMENTS)
215
+ return { ok: true, notice: 'comment stored' }
216
+ }
217
+ case 'detach': {
218
+ this.failAll(new BridgeError('浏览器页签已关闭。', 'detached'))
219
+ return { ok: true }
220
+ }
221
+ case 'hello': {
222
+ if (typeof body.version === 'string') this.version = body.version
223
+ if (typeof body.sessionId === 'string' && this.stream !== null) this.stream.sessionId = body.sessionId
224
+ return { ok: true, notice: 'hello' }
225
+ }
226
+ default:
227
+ return { ok: false, notice: `unknown report type: ${String(body?.type)}` }
228
+ }
229
+ }
230
+
231
+ /** Console entries, newest last, filtered and bounded. @param {{ level?: string, limit?: number, tabId?: string | null, since?: number }} [query] - filter. @returns {Array<object>} matching entries. */
232
+ console(query = {}) {
233
+ const limit = Math.min(Math.max(query.limit ?? 100, 1), 1000)
234
+ return this.consoleLog
235
+ .filter(entry => (query.level === undefined || entry.level === query.level))
236
+ .filter(entry => (query.tabId == null || entry.tabId === query.tabId))
237
+ .filter(entry => (typeof query.since === 'number' ? Number(entry.ts) >= query.since : true))
238
+ .slice(-limit)
239
+ }
240
+
241
+ /** Network entries, newest last. @param {{ limit?: number, failedOnly?: boolean, filter?: string }} [query] - filter. @returns {Array<object>} matching entries. */
242
+ network(query = {}) {
243
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 500)
244
+ const needle = typeof query.filter === 'string' ? query.filter.toLowerCase() : ''
245
+ return this.networkLog
246
+ .filter(entry => (query.failedOnly === true ? entry.ok !== true : true))
247
+ .filter(entry => (needle === '' ? true : String(entry.url).toLowerCase().includes(needle)))
248
+ .slice(-limit)
249
+ }
250
+
251
+ /** Comments, newest last. @param {{ selector?: string, tabId?: string | null, limit?: number }} [query] - filter. @returns {Array<object>} matching comments. */
252
+ commentsFor(query = {}) {
253
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 500)
254
+ return this.comments
255
+ .filter(entry => (query.selector === undefined ? true : entry.selector === query.selector))
256
+ .filter(entry => (query.tabId == null ? true : entry.tabId === query.tabId))
257
+ .slice(-limit)
258
+ }
259
+
260
+ /** Drop captured telemetry (console, network, optionally comments). @param {{ comments?: boolean }} [options] - what to clear. @returns {{ cleared: string[] }} what was dropped. */
261
+ clear(options = {}) {
262
+ const cleared = []
263
+ if (this.consoleLog.length > 0) { this.consoleLog = []; cleared.push('console') }
264
+ if (this.networkLog.length > 0) { this.networkLog = []; cleared.push('network') }
265
+ if (options.comments === true && this.comments.length > 0) { this.comments = []; cleared.push('comments') }
266
+ return { cleared }
267
+ }
268
+
269
+ /** One JSON-safe status snapshot for tools and /state. @returns {Record<string, unknown>} status. */
270
+ status() {
271
+ return {
272
+ connected: this.connected,
273
+ clientVersion: this.version,
274
+ sessionId: this.stream?.sessionId ?? null,
275
+ streamingSince: this.stream === null ? null : new Date(this.stream.since).toISOString(),
276
+ activeTabId: this.activeTabId,
277
+ tabs: this.tabs,
278
+ consoleEntries: this.consoleLog.length,
279
+ networkEntries: this.networkLog.length,
280
+ comments: this.comments.length,
281
+ pendingCommands: this.pending.size,
282
+ lastSeen: this.lastSeen === 0 ? null : new Date(this.lastSeen).toISOString(),
283
+ }
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Reject a request that did not come from this Host's own UI.
289
+ *
290
+ * Both carriers reach us the same way in practice: the desktop shell proxies
291
+ * the renderer's fetch through its own authenticated connection and strips the
292
+ * browser's Origin/Host headers, while the Web carrier sends a same-origin
293
+ * request. So the fence accepts a loopback Host header and, when an Origin is
294
+ * present, requires it to name the same authority.
295
+ * @param {import('node:http').IncomingMessage} req - candidate request.
296
+ * @param {string} [origin] - this server's origin, when known.
297
+ * @returns {string | null} a refusal sentence, or null when the request is fine.
298
+ */
299
+ export function fence(req, origin) {
300
+ const host = String(req.headers.host ?? '')
301
+ const hostname = host.replace(/:\d+$/u, '').replace(/^\[|\]$/gu, '').toLowerCase()
302
+ const loopback = hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '::1'
303
+ || /^127\./u.test(hostname)
304
+ let ownHost = ''
305
+ try { ownHost = origin === undefined ? '' : new URL(origin).host.toLowerCase() } catch { ownHost = '' }
306
+ if (!loopback && host.toLowerCase() !== ownHost) {
307
+ return `拒绝来自非本机地址的请求(Host: ${host || 'missing'})。`
308
+ }
309
+ const site = req.headers['sec-fetch-site']
310
+ if (typeof site === 'string' && site === 'cross-site') return '拒绝跨站请求。'
311
+ const requestOrigin = req.headers.origin
312
+ if (typeof requestOrigin === 'string' && requestOrigin !== '') {
313
+ let requestHost = ''
314
+ try { requestHost = new URL(requestOrigin).host.toLowerCase() } catch { return '拒绝来源不明的请求(Origin 无法解析)。' }
315
+ if (requestHost !== host.toLowerCase() && requestHost !== ownHost) return '拒绝跨源请求。'
316
+ }
317
+ return null
318
+ }
319
+
320
+ /**
321
+ * Read a JSON body with a hard size cap.
322
+ * @param {import('node:http').IncomingMessage} req - request.
323
+ * @param {number} [limitBytes] - cap.
324
+ * @returns {Promise<Record<string, any>>} parsed body.
325
+ */
326
+ export async function readJson(req, limitBytes = 24 * 1024 * 1024) {
327
+ const chunks = []
328
+ let total = 0
329
+ for await (const chunk of req) {
330
+ total += chunk.length
331
+ if (total > limitBytes) throw new BridgeError(`请求体超过 ${Math.round(limitBytes / 1024 / 1024)}MB 上限。`, 'too-large')
332
+ chunks.push(chunk)
333
+ }
334
+ const text = Buffer.concat(chunks).toString('utf8')
335
+ if (text.trim() === '') return {}
336
+ try {
337
+ return JSON.parse(text)
338
+ } catch {
339
+ throw new BridgeError('请求体不是合法 JSON。', 'bad-json')
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Answer a request that failed before producing a payload.
345
+ * @param {import('node:http').ServerResponse} res - response to finish.
346
+ * @param {number} status - HTTP status.
347
+ * @param {string} message - human sentence.
348
+ * @param {string} [code] - machine tag.
349
+ */
350
+ export function replyError(res, status, message, code = 'error') {
351
+ if (res.headersSent) { try { res.end() } catch { /* already finished */ } return }
352
+ const body = JSON.stringify({ ok: false, error: message, code })
353
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
354
+ res.end(body)
355
+ }
356
+
357
+ /**
358
+ * Answer a request with one JSON value.
359
+ * @param {import('node:http').ServerResponse} res - response to finish.
360
+ * @param {unknown} value - JSON payload.
361
+ * @param {number} [status] - HTTP status.
362
+ */
363
+ export function replyJson(res, value, status = 200) {
364
+ if (res.headersSent) { try { res.end() } catch { /* already finished */ } return }
365
+ const body = JSON.stringify(value)
366
+ res.writeHead(status, {
367
+ 'content-type': 'application/json; charset=utf-8',
368
+ 'cache-control': 'no-store',
369
+ 'content-length': Buffer.byteLength(body),
370
+ })
371
+ res.end(body)
372
+ }