dsh-chrome-bridge 2.0.0 → 2.0.2

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/index.js CHANGED
@@ -59,10 +59,12 @@ export function apply(ctx, config) {
59
59
  if (typeof ctx.inject === 'function') {
60
60
  ctx.inject(['webServer'], (sub) => {
61
61
  if (!sub || typeof sub.effect !== 'function' || !sub.webServer) return
62
+ const getConnection = () => (typeof ctx.get === 'function' ? ctx.get('connection') : typeof sub.get === 'function' ? sub.get('connection') : null)
62
63
  sub.effect(() => sub.webServer.register({
63
64
  kind: 'exact',
64
65
  path: PANEL_ROUTE,
65
- handler: panelHandler({ call, sock: hostUp, origin: () => sub.webServer.getOrigin(), trace }),
66
+ auth: 'required',
67
+ handler: panelHandler({ call, sock: hostUp, origin: () => sub.webServer.getOrigin(), connection: getConnection, trace }),
66
68
  }), 'chrome-bridge: settings panel route')
67
69
  trace(`设置页路由已挂上 ${PANEL_ROUTE}`)
68
70
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chrome-bridge",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "description": "DSH plugin: native browser_* tools that drive the Chrome you are already using, over native messaging + CDP. No WebSocket, no port, no Connect button. The native host and the MV3 extension ship inside this package and are installed automatically on first load; the one step left is adding the DSH Bridge extension to Chrome, from the Chrome Web Store or as the bundled unpacked copy. Until then browser_* tools fail loudly with those exact steps.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/panel.js CHANGED
@@ -5,8 +5,9 @@
5
5
  * POST /dsh-chrome-bridge/panel {action} → pause(只能暂停)/ cursor / window / releaseAll / install,回新状态
6
6
  *
7
7
  * 页面(client.js)跑在 DSH 的网页端,只能走 HTTP;这里再转成 socket 上的 `panel` 操作。
8
- * webServer 本身不做鉴权,而用户的 Chrome 里随便哪个网页都摸得到 127.0.0.1,所以自己把门:
9
- * 只收本机来的连接、跨站的 Origin 一律拒、POST 必须是 JSON(跨站发不出来,会先被预检挡住)。
8
+ * 路由同时接 DSH 宿主双代鉴权:DSH 0.2.3+ 走 webServer auth='required' 与第三参数 peer(仅放行 owner),
9
+ * DSH 0.2.2 走 connection.requestRejection(req) 验登录态,无 connection 的老宿主退回本机围栏;
10
+ * 同时对所有 POST / 跨站请求强制校 Sec-Fetch-Site、Origin 和 application/json。
10
11
  * 「恢复控制」故意不开放 —— 这条路模型也摸得到,那一下只能用户在 Chrome 的扩展面板里点。
11
12
  */
12
13
 
@@ -62,16 +63,19 @@ function handoffOf(ho) {
62
63
  return { id: ho.id ?? null, tabId: ho.tabId ?? null, reason: str(ho.reason), title: str(ho.title), url: str(ho.url), at: Number(ho.at) || 0 }
63
64
  }
64
65
 
65
- /** 跨站请求一律拒:没带 Origin(同源 GET、curl)放行;带了就必须是 DSH 自己。 */
66
- function allowed(req, origin) {
67
- if (!LOOPBACK.has(req.socket.remoteAddress)) return false
68
- if (!LOOPBACK_HOST.test(req.headers.host || '')) return false
66
+ /** 校验来源头:允许省略 Origin(同源 GET、原生客户端),带了就必须是 DSH 自己、同 Host 或桌面壳 dsh-app://app(限本机)。 */
67
+ function originAllowed(req, origin) {
68
+ const site = String(req.headers['sec-fetch-site'] || '').toLowerCase()
69
+ if (site === 'cross-site' || site === 'same-site') return false
69
70
  const from = req.headers.origin
70
71
  if (!from) return true
71
72
  if (from === 'null') return false
73
+ if (from === 'dsh-app://app') return LOOPBACK.has(req.socket.remoteAddress)
74
+ const host = String(req.headers.host || '')
75
+ if (host && (from === `http://${host}` || from === `https://${host}`)) return true
72
76
  let own
73
77
  try { own = origin() } catch { own = '' }
74
- if (from === own) return true
78
+ if (own && from === own) return true
75
79
  try {
76
80
  const a = new URL(from), b = new URL(own)
77
81
  return LOOPBACK_HOST.test(a.host) && a.port === b.port && a.protocol === b.protocol
@@ -80,6 +84,37 @@ function allowed(req, origin) {
80
84
  }
81
85
  }
82
86
 
87
+ /** 无 DSH connection 服务时的兜底本机围栏:仅本机连接、本机 Host、同源 Origin。 */
88
+ function allowed(req, origin) {
89
+ if (!LOOPBACK.has(req.socket.remoteAddress)) return false
90
+ if (!LOOPBACK_HOST.test(req.headers.host || '')) return false
91
+ return originAllowed(req, origin)
92
+ }
93
+
94
+ /**
95
+ * 双代 DSH 宿主准入检查:
96
+ * - DSH 0.2.3+:webServer 传第 3 参数 peer,仅放行 owner 主体;
97
+ * - DSH 0.2.2:调用 connection.requestRejection(req) 校验登录态与跨站围栏;
98
+ * - 若 connection 服务存在但缺失 requestRejection(版本形态不符):默认拒绝(fail-closed);
99
+ * - 无 connection 的老宿主 / 本地单测:退回本机围栏 allowed()。
100
+ * 返回 0 表示放行,否则返回 HTTP 错误码(401 / 403)。
101
+ */
102
+ function admissionStatus(req, peer, connection, origin) {
103
+ if (peer !== undefined) {
104
+ if (peer?.principal?.kind !== 'owner') return 403
105
+ return originAllowed(req, origin) ? 0 : 403
106
+ }
107
+ let conn = null
108
+ try { conn = typeof connection === 'function' ? connection() : connection } catch { conn = null }
109
+ if (conn && typeof conn.requestRejection === 'function') {
110
+ const rej = conn.requestRejection(req)
111
+ if (rej) return rej
112
+ return originAllowed(req, origin) ? 0 : 403
113
+ }
114
+ if (conn) return 403
115
+ return allowed(req, origin) ? 0 : 403
116
+ }
117
+
83
118
  function readJson(req, limit = 4096) {
84
119
  return new Promise((resolve, reject) => {
85
120
  let size = 0
@@ -99,17 +134,19 @@ function readJson(req, limit = 4096) {
99
134
  * @param deps.call - socket 调用
100
135
  * @param deps.sock - 宿主在不在的判断函数(或 socket 路径)
101
136
  * @param deps.origin - DSH 网页端自己的 origin(webServer.getOrigin)
137
+ * @param deps.connection - 可选:返回 DSH connection 服务(ctx.get('connection'))
102
138
  * @param deps.trace - 日志
103
139
  */
104
- export function panelHandler({ call, sock, origin, trace = () => {} }) {
105
- return async (req, res) => {
140
+ export function panelHandler({ call, sock, origin, connection = null, trace = () => {} }) {
141
+ return async (req, res, peer) => {
106
142
  const send = (code, body) => {
107
143
  res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
108
144
  res.end(JSON.stringify(body))
109
145
  }
110
- if (!allowed(req, origin)) {
111
- trace(`设置页路由拒绝了一个请求:${req.socket.remoteAddress} host=${req.headers.host} origin=${req.headers.origin}`)
112
- return send(403, { error: 'forbidden' })
146
+ const denied = admissionStatus(req, peer, connection, origin)
147
+ if (denied) {
148
+ trace(`设置页路由拒绝了一个请求(${denied}):${req.socket.remoteAddress} host=${req.headers.host} origin=${req.headers.origin}`)
149
+ return send(denied, { error: denied === 401 ? 'unauthorized' : 'forbidden' })
113
150
  }
114
151
  if (req.method === 'GET') return send(200, await panelState(call, sock))
115
152
  if (req.method !== 'POST') return send(405, { error: 'method not allowed' })
@@ -50,10 +50,18 @@ async function collectMarks(call, tabId) {
50
50
  const refs = [...new Set(rows.map(row => row.ref))].filter(n => n < 10000).slice(0, 80)
51
51
  if (!refs.length) return { marks: [], viewportWidth: 0, legend: '', more: 0, count: 0 }
52
52
  const r = await call('eval', { tabId, expression: MARK_BOXES_JS(refs), userGesture: false }, 15000)
53
- const marks = (r.value && Array.isArray(r.value.marks) ? r.value.marks : []).map(mark => ({
54
- ...mark,
55
- role: byRef.get(Number(mark.ref))?.role || 'clickable',
56
- }))
53
+ const marks = (r.value && Array.isArray(r.value.marks) ? r.value.marks : [])
54
+ .filter(mark => mark && Number.isInteger(Number(mark.ref)) && byRef.has(Number(mark.ref)) &&
55
+ Number.isFinite(Number(mark.x)) && Number.isFinite(Number(mark.y)) && Number(mark.width) > 1 && Number(mark.height) > 1)
56
+ .slice(0, 80)
57
+ .map(mark => ({
58
+ ref: Number(mark.ref),
59
+ x: Number(mark.x),
60
+ y: Number(mark.y),
61
+ width: Number(mark.width),
62
+ height: Number(mark.height),
63
+ role: byRef.get(Number(mark.ref))?.role || 'clickable',
64
+ }))
57
65
  const lines = rows.slice(0, 40).map(row => row.line)
58
66
  return {
59
67
  marks,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "DSH Bridge",
4
- "version": "2.0.0",
4
+ "version": "2.0.1",
5
5
  "description": "__MSG_extDescription__",
6
6
  "default_locale": "en",
7
7
  "minimum_chrome_version": "116",
@@ -86,9 +86,11 @@ async function decodeImage(base64, mime) {
86
86
  }
87
87
  }
88
88
 
89
- function canvas2d(width, height, read = false) {
89
+ function canvas2d(width, height) {
90
90
  const canvas = new OffscreenCanvas(width, height)
91
- const ctx = canvas.getContext('2d', read ? { willReadFrequently: true } : undefined)
91
+ // MV3 Service Worker 在 Windows 上默认 GPU OffscreenCanvas + DirectWrite 文本绘制会触发底层崩溃;
92
+ // 强制走 CPU 2D 软件画布(willReadFrequently),并且全部标签改用自绘像素字形,彻底绕开系统字体子系统。
93
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })
92
94
  return ctx ? { canvas, ctx } : null
93
95
  }
94
96
 
@@ -161,6 +163,55 @@ function rounded(ctx, x, y, width, height, radius) {
161
163
 
162
164
  const overlap = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y
163
165
 
166
+ const GLYPH_W = 5
167
+ const GLYPH_H = 7
168
+ const GLYPHS = {
169
+ 0: [0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e],
170
+ 1: [0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e],
171
+ 2: [0x0e, 0x11, 0x01, 0x06, 0x08, 0x10, 0x1f],
172
+ 3: [0x1e, 0x01, 0x01, 0x0e, 0x01, 0x01, 0x1e],
173
+ 4: [0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02],
174
+ 5: [0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e],
175
+ 6: [0x0e, 0x10, 0x1e, 0x11, 0x11, 0x11, 0x0e],
176
+ 7: [0x1f, 0x01, 0x02, 0x04, 0x04, 0x04, 0x04],
177
+ 8: [0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e],
178
+ 9: [0x0e, 0x11, 0x11, 0x0f, 0x01, 0x02, 0x0c],
179
+ '[': [0x0e, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0e],
180
+ ']': [0x0e, 0x02, 0x02, 0x02, 0x02, 0x02, 0x0e],
181
+ '.': [0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x0c],
182
+ s: [0x00, 0x00, 0x0f, 0x10, 0x0e, 0x01, 0x1e],
183
+ '-': [0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00],
184
+ ' ': [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
185
+ }
186
+
187
+ function measurePixelText(text, px) {
188
+ const s = String(text || '').slice(0, 32)
189
+ if (!s.length) return { width: 0, height: GLYPH_H * px }
190
+ return {
191
+ width: (s.length * (GLYPH_W + 1) - 1) * px,
192
+ height: GLYPH_H * px,
193
+ }
194
+ }
195
+
196
+ function drawPixelText(ctx, text, x, y, px) {
197
+ const s = String(text || '').slice(0, 32)
198
+ const limitX = ctx.canvas ? ctx.canvas.width : Infinity
199
+ let cursor = x
200
+ for (let i = 0; i < s.length && cursor < limitX; i++) {
201
+ const rows = GLYPHS[s[i]] || GLYPHS[' ']
202
+ for (let r = 0; r < GLYPH_H; r++) {
203
+ const bits = rows[r]
204
+ if (!bits) continue
205
+ for (let c = 0; c < GLYPH_W; c++) {
206
+ if (bits & (1 << (GLYPH_W - 1 - c))) {
207
+ ctx.fillRect(cursor + c * px, y + r * px, px, px)
208
+ }
209
+ }
210
+ }
211
+ cursor += (GLYPH_W + 1) * px
212
+ }
213
+ }
214
+
164
215
  async function drawMarks(base64, mime = 'image/jpeg', marks = [], viewportWidth = null, format, quality = 82) {
165
216
  const sourceMime = mimeOf(formatOf(mime), mime)
166
217
  const targetMime = mimeOf(format || formatOf(sourceMime), sourceMime)
@@ -176,7 +227,8 @@ async function drawMarks(base64, mime = 'image/jpeg', marks = [], viewportWidth
176
227
  const vw = Number(viewportWidth)
177
228
  const ratio = vw > 0 ? Math.max(0.25, Math.min(8, bitmap.width / vw)) : 1
178
229
  const list = marks
179
- .filter(m => m && Number.isFinite(Number(m.x)) && Number.isFinite(Number(m.y)) && Number(m.width) > 1 && Number(m.height) > 1)
230
+ .filter(m => m && Number.isInteger(Number(m.ref)) && Number(m.ref) >= 0 && Number(m.ref) <= 99999999 &&
231
+ Number.isFinite(Number(m.x)) && Number.isFinite(Number(m.y)) && Number(m.width) > 1 && Number(m.height) > 1)
180
232
  .slice(0, 80)
181
233
  if (!list.length) return { data: base64, width: bitmap.width, height: bitmap.height, mime: sourceMime, format: formatOf(sourceMime) }
182
234
 
@@ -195,18 +247,31 @@ async function drawMarks(base64, mime = 'image/jpeg', marks = [], viewportWidth
195
247
  ctx.restore()
196
248
  }
197
249
 
198
- const fontSize = Math.max(10, Math.round(12 * ratio))
199
- const padX = Math.max(3, 4 * ratio)
200
- const padY = Math.max(2, 2.5 * ratio)
201
- const gap = Math.max(2, 2 * ratio)
202
- ctx.font = `700 ${fontSize}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`
203
- ctx.textBaseline = 'middle'
250
+ const basePx = Math.max(1, Math.round(1.5 * ratio))
251
+ const basePadX = Math.max(3, Math.round(4 * ratio))
252
+ const basePadY = Math.max(2, Math.round(3 * ratio))
253
+ const gap = Math.max(2, Math.round(2 * ratio))
254
+ const shadowOff = Math.max(1, Math.round(ratio))
255
+ const maxW = Math.max(2, canvas.width - 2)
256
+ const maxH = Math.max(2, canvas.height - 2)
204
257
  const placed = []
205
258
  for (const mark of list) {
206
- const text = `[${mark.ref}]`
207
- const metrics = ctx.measureText(text)
208
- const labelWidth = Math.ceil(metrics.width + padX * 2)
209
- const labelHeight = Math.ceil(fontSize + padY * 2)
259
+ const text = `[${Number(mark.ref)}]`
260
+ let px = basePx
261
+ let padX = basePadX
262
+ let padY = basePadY
263
+ let metrics = measurePixelText(text, px)
264
+ while (px > 1 && (metrics.width + padX * 2 > maxW || metrics.height + padY * 2 > maxH)) {
265
+ px--
266
+ padX = Math.max(1, Math.round(padX * 0.7))
267
+ padY = Math.max(1, Math.round(padY * 0.7))
268
+ metrics = measurePixelText(text, px)
269
+ }
270
+ if (metrics.width + padX * 2 > maxW) padX = Math.max(1, Math.floor((maxW - metrics.width) / 2))
271
+ if (metrics.height + padY * 2 > maxH) padY = Math.max(1, Math.floor((maxH - metrics.height) / 2))
272
+ const labelWidth = Math.min(maxW, Math.ceil(metrics.width + padX * 2))
273
+ const labelHeight = Math.min(maxH, Math.ceil(metrics.height + padY * 2))
274
+ const radius = Math.min(Math.max(2, Math.round(4 * ratio)), labelWidth / 2, labelHeight / 2)
210
275
  const ex = Number(mark.x) * ratio
211
276
  const ey = Number(mark.y) * ratio
212
277
  const box = {
@@ -223,19 +288,22 @@ async function drawMarks(base64, mime = 'image/jpeg', marks = [], viewportWidth
223
288
  }
224
289
  placed.push(box)
225
290
  const color = colorForRole(mark.role)
291
+ const shadowY = Math.max(box.y, Math.min(canvas.height - box.height, box.y + shadowOff))
226
292
  ctx.save()
227
- ctx.shadowColor = 'rgba(0, 0, 0, 0.55)'
228
- ctx.shadowBlur = Math.max(1, 1.5 * ratio)
229
- ctx.shadowOffsetY = Math.max(0.5, ratio)
230
- rounded(ctx, box.x, box.y, box.width, box.height, Math.max(3, 4 * ratio))
293
+ rounded(ctx, box.x, shadowY, box.width, box.height, radius)
294
+ ctx.fillStyle = 'rgba(0, 0, 0, 0.45)'
295
+ ctx.fill()
296
+ rounded(ctx, box.x, box.y, box.width, box.height, radius)
231
297
  ctx.fillStyle = color
232
298
  ctx.fill()
233
- ctx.shadowColor = 'transparent'
234
299
  ctx.lineWidth = Math.max(1, 1.1 * ratio)
235
300
  ctx.strokeStyle = '#ffffff'
236
301
  ctx.stroke()
302
+ ctx.beginPath()
303
+ ctx.rect(box.x, box.y, box.width, box.height)
304
+ ctx.clip()
237
305
  ctx.fillStyle = '#ffffff'
238
- ctx.fillText(text, box.x + padX, box.y + box.height / 2 + 0.5)
306
+ drawPixelText(ctx, text, Math.round(box.x + Math.max(1, (box.width - metrics.width) / 2)), Math.round(box.y + Math.max(0, (box.height - metrics.height) / 2)), px)
239
307
  ctx.restore()
240
308
  }
241
309
  return { ...await encodeCanvas(canvas, targetMime, quality), marked: true }
@@ -274,7 +342,7 @@ async function decodeFramesToRgb(frames, targetWidth = 640) {
274
342
  result.width = width
275
343
  result.height = height
276
344
  }
277
- const target = canvas2d(width, height, true)
345
+ const target = canvas2d(width, height)
278
346
  if (!target) continue
279
347
  target.ctx.imageSmoothingEnabled = true
280
348
  target.ctx.imageSmoothingQuality = 'high'
@@ -333,14 +401,24 @@ async function buildContactSheet(frames, { cols = 3, rows = 3, cellWidth = 360 }
333
401
  ctx.drawImage(bitmap, x, y, cw, ch)
334
402
  const at = Number(picked[i].frame && picked[i].frame.atMs) || 0
335
403
  const label = `${((at - base) / 1000).toFixed(1)}s`
336
- ctx.font = '700 13px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
337
- ctx.textBaseline = 'middle'
338
- const w = Math.ceil(ctx.measureText(label).width + 12)
404
+ const compact = ch < 32
405
+ const px = compact ? 1 : 2
406
+ const pad = compact ? 1 : 5
407
+ const padX = compact ? 3 : 6
408
+ const padY = compact ? 2 : 4
409
+ const metrics = measurePixelText(label, px)
410
+ const w = Math.min(Math.max(2, cw - pad * 2), Math.ceil(metrics.width + padX * 2))
411
+ const h = Math.min(Math.max(2, ch - pad * 2), Math.ceil(metrics.height + padY * 2))
412
+ ctx.save()
413
+ ctx.beginPath()
414
+ ctx.rect(x, y, cw, ch)
415
+ ctx.clip()
339
416
  ctx.fillStyle = 'rgba(0, 0, 0, 0.68)'
340
- rounded(ctx, x + 5, y + 5, w, 22, 5)
417
+ rounded(ctx, x + pad, y + pad, w, h, Math.min(compact ? 3 : 5, w / 2, h / 2))
341
418
  ctx.fill()
342
419
  ctx.fillStyle = '#ffffff'
343
- ctx.fillText(label, x + 11, y + 16)
420
+ drawPixelText(ctx, label, x + pad + Math.max(1, Math.round((w - metrics.width) / 2)), y + pad + Math.max(0, Math.round((h - metrics.height) / 2)), px)
421
+ ctx.restore()
344
422
  } finally {
345
423
  bitmap.close?.()
346
424
  }