@sparkelf/dsh-mobile-bridge-server 0.2.11 → 0.2.13

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparkelf/dsh-mobile-bridge-server",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "type": "module",
5
5
  "description": "Multi-user bridge server connecting mobile browsers to local DeepSeek Harness instances through outbound tunnels.",
6
6
  "license": "MIT",
package/src/phone.ts CHANGED
@@ -45,35 +45,114 @@ export const PWA_MANIFEST = JSON.stringify({
45
45
  ],
46
46
  })
47
47
 
48
- /** One-tap install guide: captures beforeinstallprompt; iOS gets a share-sheet hint once. */
48
+ /**
49
+ * Always-visible install entry for the paired phone view: the floating button
50
+ * shows on every relayed page without waiting for Chrome's engagement-gated
51
+ * beforeinstallprompt. A captured prompt installs in one tap; otherwise the
52
+ * button opens per-browser manual steps (iOS share sheet / Android ⋮ menu /
53
+ * switch-browser advice). Installing OR dismissing hides the button and
54
+ * persists a flag so it never auto-returns; the guide says installation stays
55
+ * available from the browser menu. Standalone display mode is hidden from the
56
+ * first load.
57
+ */
49
58
  export const PWA_INSTALL_SOURCE = `/* DSH mobile bridge PWA install guide. */
50
59
  (function () {
51
- if (window.matchMedia('(display-mode: standalone)').matches || navigator.standalone) return
60
+ var INSTALLED_KEY = 'dsh-bridge-pwa-installed'
61
+ var DISMISSED_KEY = 'dsh-bridge-pwa-dismissed'
62
+ function flag(key) { try { return localStorage.getItem(key) === '1' } catch (err) { return false } }
63
+ function persist(key) { try { localStorage.setItem(key, '1') } catch (err) {} }
64
+ function isHidden() {
65
+ return flag(INSTALLED_KEY) || flag(DISMISSED_KEY) || window.matchMedia('(display-mode: standalone)').matches || navigator.standalone === true
66
+ }
67
+ if (isHidden()) return
52
68
  var deferred = null
53
69
  var btn = null
70
+ var closeBtn = null
71
+ function hideBtn() {
72
+ if (btn) { btn.remove(); btn = null }
73
+ if (closeBtn) { closeBtn.remove(); closeBtn = null }
74
+ }
75
+ function dismiss() { persist(DISMISSED_KEY); hideBtn() }
54
76
  function ensureBtn() {
55
77
  if (btn) return btn
78
+ if (isHidden()) return null
56
79
  btn = document.createElement('button')
80
+ btn.id = 'dsh-pwa-install-btn'
57
81
  btn.textContent = '安装到主屏幕'
58
82
  btn.style.cssText = 'position:fixed;left:50%;transform:translateX(-50%);bottom:18px;z-index:99999;height:44px;padding:0 22px;border:0;border-radius:22px;background:#405de6;color:#fff;font:600 14px system-ui,sans-serif;box-shadow:0 6px 24px rgba(64,93,230,.4)'
59
83
  btn.onclick = function () {
60
- if (deferred) { deferred.prompt(); deferred.userChoice.then(function () { deferred = null; if (btn) { btn.remove(); btn = null } }) }
61
- else showIos()
84
+ if (deferred) {
85
+ var promptEvent = deferred
86
+ deferred = null
87
+ promptEvent.prompt()
88
+ promptEvent.userChoice.then(function (choice) { if (choice && choice.outcome === 'accepted') { persist(INSTALLED_KEY); hideBtn() } })
89
+ return
90
+ }
91
+ showGuide()
62
92
  }
93
+ closeBtn = document.createElement('button')
94
+ closeBtn.id = 'dsh-pwa-install-close'
95
+ closeBtn.textContent = '×'
96
+ closeBtn.style.cssText = 'position:fixed;left:50%;transform:translateX(76px);bottom:24px;z-index:99999;width:32px;height:32px;border:0;border-radius:16px;background:rgba(13,16,21,.72);color:#aeb8c8;font:600 16px system-ui,sans-serif;line-height:1'
97
+ closeBtn.onclick = function (event) { if (event && event.stopPropagation) event.stopPropagation(); dismiss() }
63
98
  document.body.appendChild(btn)
99
+ document.body.appendChild(closeBtn)
64
100
  return btn
65
101
  }
66
- function showIos() {
102
+ function guideKind() {
103
+ var ua = navigator.userAgent || ''
104
+ if (/iphone|ipad|ipod/i.test(ua) || (/macintosh/i.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
105
+ if (/android/i.test(ua) && /chrome\\//i.test(ua)) return 'android'
106
+ return 'other'
107
+ }
108
+ function showGuide() {
109
+ var kind = guideKind()
110
+ var ua = navigator.userAgent || ''
111
+ var title = '安装到主屏幕'
112
+ var steps
113
+ if (kind === 'ios') {
114
+ title = '添加到主屏幕'
115
+ var safari = /safari/i.test(ua) && !/crios|fxios|edgios/i.test(ua)
116
+ steps = (safari ? '' : '请先在 Safari 中打开本页,然后:\\n') + '1. 点 Safari 底部「分享」按钮(方框向上箭头)\\n2. 选择「添加到主屏幕」\\n3. 点右上角「添加」,即可像 App 一样打开'
117
+ } else if (kind === 'android') {
118
+ title = '安装应用'
119
+ steps = '1. 点浏览器右上角 ⋮(三个点)菜单\\n2. 选择「安装应用」或「添加到主屏幕」\\n3. 确认安装,即可像 App 一样打开'
120
+ } else {
121
+ steps = '当前浏览器暂不支持一键安装。\\n请用 Chrome(Android)或 Safari(iPhone/iPad)打开本页,\\n再点「安装到主屏幕」按钮。'
122
+ }
67
123
  var ov = document.createElement('div')
124
+ ov.id = 'dsh-pwa-guide'
68
125
  ov.style.cssText = 'position:fixed;inset:0;z-index:100000;background:rgba(13,16,21,.92);color:#f4f7fb;display:grid;place-items:center;font:14px/1.7 system-ui,sans-serif;text-align:center;padding:24px'
69
- ov.innerHTML = '<div><p style="font-size:16px;font-weight:650">添加到主屏幕</p><p>点 Safari 底部「分享」按钮,<br>选择「添加到主屏幕」,即可像 App 一样打开。</p><button style="margin-top:18px;height:40px;padding:0 20px;border:0;border-radius:20px;background:#405de6;color:#fff">知道了</button></div>'
70
- ov.querySelector('button').onclick = function () { ov.remove(); localStorage.setItem('dsh-bridge-pwa-ios-hint', '1') }
126
+ var card = document.createElement('div')
127
+ var heading = document.createElement('p')
128
+ heading.style.cssText = 'font-size:16px;font-weight:650;margin:0 0 10px'
129
+ heading.textContent = title
130
+ var body = document.createElement('p')
131
+ body.style.cssText = 'margin:0;white-space:pre-line'
132
+ body.textContent = steps
133
+ var note = document.createElement('p')
134
+ note.style.cssText = 'margin:14px 0 0;font-size:12px;color:#aeb8c8'
135
+ note.textContent = '关闭后不再显示此按钮;之后仍可随时在浏览器菜单中安装。'
136
+ var ok = document.createElement('button')
137
+ ok.textContent = '知道了'
138
+ ok.style.cssText = 'margin-top:18px;height:40px;padding:0 20px;border:0;border-radius:20px;background:#405de6;color:#fff;font:600 14px system-ui,sans-serif'
139
+ ok.onclick = function () { ov.remove(); dismiss() }
140
+ card.appendChild(heading)
141
+ card.appendChild(body)
142
+ card.appendChild(note)
143
+ card.appendChild(ok)
144
+ ov.appendChild(card)
145
+ ov.onclick = function (event) { if (event && event.target === ov) { ov.remove(); dismiss() } }
71
146
  document.body.appendChild(ov)
72
147
  }
73
148
  window.addEventListener('beforeinstallprompt', function (e) { e.preventDefault(); deferred = e; ensureBtn() })
74
- window.addEventListener('appinstalled', function () { if (btn) { btn.remove(); btn = null } deferred = null })
75
- var ios = /iphone|ipad|ipod/i.test(navigator.userAgent) && /safari/i.test(navigator.userAgent)
76
- if (ios && !localStorage.getItem('dsh-bridge-pwa-ios-hint')) setTimeout(function () { ensureBtn(); showIos() }, 2500)
149
+ window.addEventListener('appinstalled', function () {
150
+ try { localStorage.setItem(INSTALLED_KEY, '1') } catch (err) {}
151
+ deferred = null
152
+ hideBtn()
153
+ })
154
+ if (document.body) ensureBtn()
155
+ else document.addEventListener('DOMContentLoaded', function () { ensureBtn() })
77
156
  })()
78
157
  `
79
158
 
@@ -85,6 +164,46 @@ let keyPromise = null
85
164
  let revoked = false
86
165
  const PAIR_CACHE = 'dsh-mobile-bridge-pair-v1'
87
166
  const PAIR_CACHE_KEY = '/bridge/.pair-state'
167
+ // Decrypted static assets live in a per-pair CacheStorage bucket. The bucket
168
+ // name carries a short digest of the pair key material (never the raw secret),
169
+ // so a key rotation renames the bucket and the old decrypted bytes are pruned.
170
+ const ASSET_CACHE_PREFIX = 'dshmb-assets-'
171
+ const ASSET_EXT = /\\.(m?js|css|png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf|eot|wasm)$/i
172
+ let assetCachePromise = null
173
+ async function pairKeyId(pair) {
174
+ const material = new TextEncoder().encode('dsh-mobile-bridge/assets/v1:' + (pair.k ?? '') + ':' + pair.s)
175
+ const digest = await crypto.subtle.digest('SHA-256', material)
176
+ return Array.from(new Uint8Array(digest)).slice(0, 8).map(byte => byte.toString(16).padStart(2, '0')).join('')
177
+ }
178
+ function assetCache() {
179
+ if (!assetCachePromise) {
180
+ assetCachePromise = (async () => {
181
+ const name = ASSET_CACHE_PREFIX + await pairKeyId(pairValue)
182
+ const stale = (await caches.keys()).filter(key => key.startsWith(ASSET_CACHE_PREFIX) && key !== name)
183
+ await Promise.all(stale.map(key => caches.delete(key)))
184
+ return caches.open(name)
185
+ })().catch(error => { assetCachePromise = null; throw error })
186
+ }
187
+ return assetCachePromise
188
+ }
189
+ function htmlHasRev(url) {
190
+ return /[?&](rev|v|hash|version)=/i.test(url.search) || /[.-][0-9a-f]{8,}\\.html?$/i.test(url.pathname)
191
+ }
192
+ // Only GET static assets and the HTML shell are cacheable. API paths, SSE,
193
+ // range requests, no-store and every non-GET method stay on the live relay.
194
+ function assetCachePlan(request, url) {
195
+ if (request.method !== 'GET') return null
196
+ if (request.cache === 'no-store') return null
197
+ if (url.pathname === '/api' || url.pathname.startsWith('/api/')) return null
198
+ const accept = request.headers.get('accept') ?? ''
199
+ if (accept.includes('text/event-stream')) return null
200
+ if (request.headers.get('range') !== null) return null
201
+ if (request.mode === 'navigate' || accept.includes('text/html') || /\\.html?$/i.test(url.pathname)) {
202
+ return { key: url.href, mode: htmlHasRev(url) ? 'first' : 'swr' }
203
+ }
204
+ if (ASSET_EXT.test(url.pathname)) return { key: url.href, mode: 'first' }
205
+ return null
206
+ }
88
207
  async function waitForPair() {
89
208
  if (pairValue) return pairValue
90
209
  const cache = await caches.open(PAIR_CACHE)
@@ -108,7 +227,7 @@ self.addEventListener('message', event => {
108
227
  if (!revoked) {
109
228
  const replacedError = new Error('pair replaced')
110
229
  for (const entry of pending.values()) {
111
- if (entry.websocketPort) { entry.websocketPort.postMessage({ kind: 'websocket-error', message: replacedError.message }); entry.websocketPort.close() }
230
+ if (entry.websocketPort) { if (entry.openTimer != null) clearTimeout(entry.openTimer); entry.websocketPort.postMessage({ kind: 'websocket-error', message: replacedError.message }); entry.websocketPort.close() }
112
231
  else if (entry.controller) entry.controller.error(replacedError)
113
232
  else entry.reject(replacedError)
114
233
  }
@@ -116,11 +235,14 @@ self.addEventListener('message', event => {
116
235
  pending.clear()
117
236
  pairValue = event.data.pair
118
237
  keyPromise = null
238
+ assetCachePromise = null
119
239
  revoked = false
120
240
  for (const resolve of pairWaiters) resolve(pairValue)
121
241
  pairWaiters = []
122
242
  const persist = caches.open(PAIR_CACHE).then(cache => cache.put(PAIR_CACHE_KEY, new Response(JSON.stringify({ pair: pairValue }), { headers: { 'content-type': 'application/json' } })))
123
243
  event.waitUntil(persist.then(() => { event.ports[0].postMessage({ ready: true }) }))
244
+ // Rotation: open the new per-pair bucket and delete every older one.
245
+ event.waitUntil(assetCache().catch(error => { console.error('[dsh-mobile-bridge] asset cache rotation failed', error) }))
124
246
  return
125
247
  }
126
248
  if (event.data.type === 'application-websocket') {
@@ -163,6 +285,7 @@ function wsReady() {
163
285
  const settlePending = () => {
164
286
  for (const entry of pending.values()) {
165
287
  if (entry.websocketPort) {
288
+ if (entry.openTimer != null) clearTimeout(entry.openTimer)
166
289
  entry.websocketPort.postMessage({ kind: 'websocket-error', message: error.message })
167
290
  entry.websocketPort.close()
168
291
  } else if (entry.controller) {
@@ -174,6 +297,7 @@ function wsReady() {
174
297
  if (event.code === 4003 && isCurrent) {
175
298
  pairValue = null
176
299
  keyPromise = null
300
+ assetCachePromise = null
177
301
  revoked = true
178
302
  void caches.open(PAIR_CACHE).then(cache => cache.put(PAIR_CACHE_KEY, new Response(JSON.stringify({ revoked: true }), { headers: { 'content-type': 'application/json' } }))).catch(error => { console.error('[dsh-mobile-bridge] revoked pair persistence failed', error) })
179
303
  void self.clients.matchAll({ type: 'window' })
@@ -191,6 +315,7 @@ function wsReady() {
191
315
  if (!entry) return
192
316
  if (entry.websocketPort) {
193
317
  void decryptJSON(entry.key, frame.blob).then(payload => {
318
+ if (payload.kind === 'websocket-open' && entry.openTimer != null) { clearTimeout(entry.openTimer); entry.openTimer = null }
194
319
  entry.websocketPort.postMessage(payload)
195
320
  if (payload.kind === 'websocket-close') { entry.websocketPort.close(); pending.delete(frame.id) }
196
321
  }).catch(error => {
@@ -217,21 +342,47 @@ function wsReady() {
217
342
  body = new TextEncoder().encode(html)
218
343
  }
219
344
  pending.delete(frame.id)
220
- entry.resolve(new Response(body, { status: full.status, headers: full.headers }))
345
+ const response = new Response(body, { status: full.status, headers: full.headers })
346
+ if (entry.cache && entry.cacheKey && full.status === 200) {
347
+ void entry.cache.put(entry.cacheKey, response.clone()).catch(error => { console.error('[dsh-mobile-bridge] asset cache put failed', error) })
348
+ }
349
+ entry.resolve(response)
221
350
  })().catch(error => { console.error('[dsh-mobile-bridge] response decrypt failed', error); if (entry.controller) entry.controller.error(error); else entry.reject(error); pending.delete(frame.id) })
222
351
  }
223
352
  })
224
353
  return wsPromise
225
354
  }
226
355
 
356
+ // Application-WS open handshake deadline. Slow mobile links used to hang the
357
+ // app's stream open forever; a generous configurable default fails fast into a
358
+ // retry instead. Page localStorage override wins over pair config, then 15s.
359
+ const STREAM_OPEN_TIMEOUT_DEFAULT = 15000
360
+ function resolveStreamOpenTimeout(command, pair) {
361
+ const candidates = [command && command.streamOpenTimeoutMs, pair && pair.streamOpenTimeoutMs]
362
+ for (const value of candidates) {
363
+ const parsed = typeof value === 'string' ? parseInt(value, 10) : value
364
+ if (typeof parsed === 'number' && Number.isFinite(parsed) && parsed >= 1000 && parsed <= 120000) return parsed
365
+ }
366
+ return STREAM_OPEN_TIMEOUT_DEFAULT
367
+ }
368
+
227
369
  async function openApplicationSocket(command, port) {
228
370
  const pair = await waitForPair()
229
371
  if (revoked) throw new Error('device revoked')
230
372
  if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
231
373
  const key = await keyPromise
232
- const ws = await wsReady()
233
374
  const id = 'w' + (++counter)
234
- pending.set(id, { key, websocketPort: port })
375
+ let ws
376
+ const entry = { key, websocketPort: port, openTimer: null }
377
+ pending.set(id, entry)
378
+ const failOpen = message => {
379
+ if (pending.get(id) !== entry) return
380
+ pending.delete(id)
381
+ if (entry.openTimer != null) { clearTimeout(entry.openTimer); entry.openTimer = null }
382
+ port.postMessage({ kind: 'websocket-error', message })
383
+ port.close()
384
+ }
385
+ entry.openTimer = setTimeout(() => failOpen('stream open timed out'), resolveStreamOpenTimeout(command, pair))
235
386
  port.onmessage = event => {
236
387
  void (async () => {
237
388
  const message = event.data
@@ -245,8 +396,14 @@ async function openApplicationSocket(command, port) {
245
396
  })
246
397
  }
247
398
  port.start()
248
- const blob = await encryptJSON(key, { kind: 'websocket-open', path: command.path, protocols: command.protocols })
249
- ws.send(JSON.stringify({ id, blob }))
399
+ try {
400
+ ws = await wsReady()
401
+ const blob = await encryptJSON(key, { kind: 'websocket-open', path: command.path, protocols: command.protocols })
402
+ ws.send(JSON.stringify({ id, blob }))
403
+ } catch (error) {
404
+ failOpen(error.message || 'stream open failed')
405
+ throw error
406
+ }
250
407
  }
251
408
 
252
409
  function revokedResponse() {
@@ -254,6 +411,49 @@ function revokedResponse() {
254
411
  return new Response(html, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8' } })
255
412
  }
256
413
 
414
+ // One live relay round trip. Cacheable GETs carry their bucket so the decrypted
415
+ // 200 response is written back after decryption; everything else is unchanged.
416
+ async function relayFetch(request, url, pair, plan, cache) {
417
+ if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
418
+ const key = await keyPromise
419
+ const bodyBytes = new Uint8Array(await request.arrayBuffer())
420
+ const id = 'r' + (++counter)
421
+ const headers = { accept: request.headers.get('accept') ?? '' }
422
+ const contentType = request.headers.get('content-type')
423
+ if (contentType !== null) headers['content-type'] = contentType
424
+ const blob = await encryptJSON(key, {
425
+ kind: 'http',
426
+ method: request.method,
427
+ path: url.pathname + url.search,
428
+ headers,
429
+ body: bytesToBase64(bodyBytes),
430
+ bodyEncoding: 'base64',
431
+ })
432
+ let ws
433
+ try {
434
+ ws = await wsReady()
435
+ } catch (error) {
436
+ if (revoked) return revokedResponse()
437
+ console.error('[dsh-mobile-bridge] bridge connection failed', error)
438
+ return new Response('Mobile Bridge connection failed', { status: 502 })
439
+ }
440
+ if ((request.headers.get('accept') ?? '').includes('text/event-stream')) {
441
+ return new Promise((resolve, reject) => {
442
+ let controller
443
+ const readable = new ReadableStream({
444
+ start(value) { controller = value },
445
+ cancel() { pending.delete(id) },
446
+ })
447
+ pending.set(id, { key, controller, resolve: () => resolve(new Response(readable, { headers: { 'content-type': 'text/event-stream' } })), reject, status: 200, headers: {} })
448
+ ws.send(JSON.stringify({ id, blob, streamHint: true }))
449
+ })
450
+ }
451
+ return new Promise((resolve, reject) => {
452
+ pending.set(id, { key, resolve, reject, cache: plan && cache ? cache : null, cacheKey: plan ? plan.key : null })
453
+ ws.send(JSON.stringify({ id, blob }))
454
+ })
455
+ }
456
+
257
457
  self.addEventListener('fetch', event => {
258
458
  const url = new URL(event.request.url)
259
459
  if (url.pathname.startsWith('/bridge') || url.pathname === '/sw.js' || url.pathname.startsWith('/ws')) return
@@ -269,45 +469,26 @@ self.addEventListener('fetch', event => {
269
469
  if (event.request.mode === 'navigate') return revokedResponse()
270
470
  return new Promise(() => {})
271
471
  }
272
- if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
273
- const key = await keyPromise
274
472
  const request = event.request
275
- const bodyBytes = new Uint8Array(await request.arrayBuffer())
276
- const id = 'r' + (++counter)
277
- const headers = { accept: request.headers.get('accept') ?? '' }
278
- const contentType = request.headers.get('content-type')
279
- if (contentType !== null) headers['content-type'] = contentType
280
- const blob = await encryptJSON(key, {
281
- kind: 'http',
282
- method: request.method,
283
- path: url.pathname + url.search,
284
- headers,
285
- body: bytesToBase64(bodyBytes),
286
- bodyEncoding: 'base64',
287
- })
288
- let ws
289
- try {
290
- ws = await wsReady()
291
- } catch (error) {
292
- if (revoked) return revokedResponse()
293
- console.error('[dsh-mobile-bridge] bridge connection failed', error)
294
- return new Response('Mobile Bridge connection failed', { status: 502 })
295
- }
296
- if ((request.headers.get('accept') ?? '').includes('text/event-stream')) {
297
- return new Promise((resolve, reject) => {
298
- let controller
299
- const readable = new ReadableStream({
300
- start(value) { controller = value },
301
- cancel() { pending.delete(id) },
302
- })
303
- pending.set(id, { key, controller, resolve: () => resolve(new Response(readable, { headers: { 'content-type': 'text/event-stream' } })), reject, status: 200, headers: {} })
304
- ws.send(JSON.stringify({ id, blob, streamHint: true }))
305
- })
473
+ const plan = assetCachePlan(request, url)
474
+ let cache = null
475
+ if (plan) {
476
+ try {
477
+ cache = await assetCache()
478
+ const hit = await cache.match(plan.key)
479
+ if (hit) {
480
+ // Un-versioned shell: render the cached bytes now, refresh in background.
481
+ if (plan.mode === 'swr') {
482
+ event.waitUntil(relayFetch(request, url, pair, plan, cache).catch(error => { console.error('[dsh-mobile-bridge] asset revalidation failed', error) }))
483
+ }
484
+ return hit
485
+ }
486
+ } catch (error) {
487
+ console.error('[dsh-mobile-bridge] asset cache unavailable', error)
488
+ cache = null
489
+ }
306
490
  }
307
- return new Promise((resolve, reject) => {
308
- pending.set(id, { key, resolve, reject })
309
- ws.send(JSON.stringify({ id, blob }))
310
- })
491
+ return relayFetch(request, url, pair, plan, cache)
311
492
  })())
312
493
  })
313
494
  `
@@ -363,7 +544,12 @@ export const SOCKET_CLIENT_SOURCE = `/* E2EE WebSocket facade for the relayed Ha
363
544
  }
364
545
  this._port.port1.start()
365
546
  var protocolList = protocols === undefined ? [] : (Array.isArray(protocols) ? protocols : [protocols])
366
- navigator.serviceWorker.controller.postMessage({ type: 'application-websocket', path: target.pathname + target.search, protocols: protocolList }, [this._port.port2])
547
+ var streamOpenTimeoutMs
548
+ try {
549
+ var rawTimeout = localStorage.getItem('dshmb-stream-open-timeout-ms')
550
+ if (rawTimeout !== null) { var parsedTimeout = parseInt(rawTimeout, 10); if (isFinite(parsedTimeout) && parsedTimeout > 0) streamOpenTimeoutMs = parsedTimeout }
551
+ } catch (err) {}
552
+ navigator.serviceWorker.controller.postMessage({ type: 'application-websocket', path: target.pathname + target.search, protocols: protocolList, streamOpenTimeoutMs: streamOpenTimeoutMs }, [this._port.port2])
367
553
  }
368
554
  _emit(event) {
369
555
  this.dispatchEvent(event)
package/src/pwa.spec.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import { afterEach, describe, expect, it } from 'vitest'
2
+ import { webcrypto } from 'node:crypto'
2
3
  import { mkdtempSync, rmSync } from 'node:fs'
3
4
  import { tmpdir } from 'node:os'
4
5
  import { join } from 'node:path'
5
6
  import type { AddressInfo } from 'node:net'
6
7
  import { createBridgeServer } from './server.ts'
7
8
  import { UserStore } from './store.ts'
8
- import { CLIENT_SOURCE, PWA_HEAD, SW_SOURCE } from './phone.ts'
9
- import { Script } from 'node:vm'
9
+ import { CLIENT_SOURCE, PWA_HEAD, PWA_INSTALL_SOURCE, SOCKET_CLIENT_SOURCE, SW_SOURCE } from './phone.ts'
10
+ import { Script, createContext } from 'node:vm'
10
11
 
11
12
  const open: Array<{ close: () => void }> = []
12
13
  afterEach(() => { for (const entry of open.splice(0)) entry.close() })
@@ -73,3 +74,655 @@ describe('phone PWA install surface', () => {
73
74
  expect(() => new Script(SW_SOURCE)).not.toThrow()
74
75
  })
75
76
  })
77
+
78
+ /** Minimal DOM element stub: only what the install guide touches. */
79
+ type StubElement = {
80
+ tagName: string
81
+ id: string
82
+ textContent: string
83
+ style: { cssText: string }
84
+ children: StubElement[]
85
+ parent: StubElement | null
86
+ onclick: ((event?: { target?: StubElement; stopPropagation?: () => void }) => void) | null
87
+ appendChild(child: StubElement): StubElement
88
+ remove(): void
89
+ }
90
+
91
+ function makeElement(tagName: string): StubElement {
92
+ const el: StubElement = {
93
+ tagName,
94
+ id: '',
95
+ textContent: '',
96
+ style: { cssText: '' },
97
+ children: [],
98
+ parent: null,
99
+ onclick: null,
100
+ appendChild(child) { child.parent = el; el.children.push(child); return child },
101
+ remove() {
102
+ if (el.parent) el.parent.children = el.parent.children.filter(child => child !== el)
103
+ el.parent = null
104
+ },
105
+ }
106
+ return el
107
+ }
108
+
109
+ const UA = {
110
+ androidChrome: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36',
111
+ iphoneSafari: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
112
+ ipadMac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15',
113
+ iphoneChrome: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/126.0.6478.54 Mobile/15E148 Safari/604.1',
114
+ desktopFirefox: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0',
115
+ }
116
+
117
+ /** Run the real install guide in a vm with a stub DOM; returns observation handles. */
118
+ function runInstallGuide(opts: { ua: string; standalone?: boolean; iosStandalone?: boolean; installed?: boolean; dismissed?: boolean; touchPoints?: number; bodyReady?: boolean }) {
119
+ const windowListeners = new Map<string, Array<(event: unknown) => void>>()
120
+ const docListeners = new Map<string, Array<() => void>>()
121
+ const storage = new Map<string, string>()
122
+ if (opts.installed) storage.set('dsh-bridge-pwa-installed', '1')
123
+ if (opts.dismissed) storage.set('dsh-bridge-pwa-dismissed', '1')
124
+ const body = makeElement('body')
125
+ const doc = {
126
+ body: opts.bodyReady === false ? null : body,
127
+ createElement: makeElement,
128
+ addEventListener: (name: string, fn: () => void) => {
129
+ const list = docListeners.get(name) ?? []
130
+ list.push(fn)
131
+ docListeners.set(name, list)
132
+ },
133
+ }
134
+ const sandbox = {
135
+ window: {
136
+ matchMedia: (query: string) => ({ matches: query === '(display-mode: standalone)' && opts.standalone === true }),
137
+ addEventListener: (name: string, fn: (event: unknown) => void) => {
138
+ const list = windowListeners.get(name) ?? []
139
+ list.push(fn)
140
+ windowListeners.set(name, list)
141
+ },
142
+ },
143
+ navigator: { userAgent: opts.ua, standalone: opts.iosStandalone === true ? true : undefined, maxTouchPoints: opts.touchPoints ?? 0 },
144
+ localStorage: {
145
+ getItem: (key: string) => storage.get(key) ?? null,
146
+ setItem: (key: string, value: string) => { storage.set(key, value) },
147
+ },
148
+ document: doc,
149
+ }
150
+ createContext(sandbox)
151
+ new Script(PWA_INSTALL_SOURCE).runInContext(sandbox)
152
+ const textOf = (el: StubElement): string => el.textContent + el.children.map(textOf).join('')
153
+ return {
154
+ body,
155
+ storage,
156
+ fire: (name: string, event: unknown) => { for (const fn of windowListeners.get(name) ?? []) fn(event) },
157
+ domReady: () => { doc.body = body; for (const fn of docListeners.get('DOMContentLoaded') ?? []) fn() },
158
+ findBtn: () => body.children.find(child => child.id === 'dsh-pwa-install-btn'),
159
+ findClose: () => body.children.find(child => child.id === 'dsh-pwa-install-close'),
160
+ findGuide: () => body.children.find(child => child.id === 'dsh-pwa-guide'),
161
+ guideText: () => { const guide = body.children.find(child => child.id === 'dsh-pwa-guide'); return guide ? textOf(guide) : '' },
162
+ }
163
+ }
164
+
165
+ const flush = () => new Promise(resolve => setTimeout(resolve, 0))
166
+
167
+ describe('PWA install entry behavior (vm)', () => {
168
+ it('shows the floating button on load without any beforeinstallprompt', () => {
169
+ const guide = runInstallGuide({ ua: UA.androidChrome })
170
+ const btn = guide.findBtn()
171
+ expect(btn).toBeDefined()
172
+ expect(btn?.textContent).toBe('安装到主屏幕')
173
+ expect(btn?.style.cssText).toContain('position:fixed')
174
+ expect(guide.findGuide()).toBeUndefined()
175
+ })
176
+
177
+ it('defers the button to DOMContentLoaded when injected into <head> before body exists', () => {
178
+ const guide = runInstallGuide({ ua: UA.androidChrome, bodyReady: false })
179
+ expect(guide.findBtn()).toBeUndefined()
180
+ guide.domReady()
181
+ expect(guide.findBtn()).toBeDefined()
182
+ })
183
+
184
+ it('click without a deferred prompt opens the iOS Safari share-sheet steps', () => {
185
+ const guide = runInstallGuide({ ua: UA.iphoneSafari })
186
+ guide.findBtn()?.onclick?.()
187
+ const text = guide.guideText()
188
+ expect(text).toContain('添加到主屏幕')
189
+ expect(text).toContain('分享')
190
+ expect(text).not.toContain('请先在 Safari 中打开本页')
191
+ expect(guide.findGuide()?.style.cssText).toContain('position:fixed')
192
+ })
193
+
194
+ it('treats iPadOS masquerading as Macintosh as iOS', () => {
195
+ const guide = runInstallGuide({ ua: UA.ipadMac, touchPoints: 5 })
196
+ guide.findBtn()?.onclick?.()
197
+ expect(guide.guideText()).toContain('分享')
198
+ })
199
+
200
+ it('tells iOS non-Safari browsers to open Safari first', () => {
201
+ const guide = runInstallGuide({ ua: UA.iphoneChrome })
202
+ guide.findBtn()?.onclick?.()
203
+ expect(guide.guideText()).toContain('请先在 Safari 中打开本页')
204
+ })
205
+
206
+ it('click without a deferred prompt opens the Android Chrome ⋮ menu steps', () => {
207
+ const guide = runInstallGuide({ ua: UA.androidChrome })
208
+ guide.findBtn()?.onclick?.()
209
+ const text = guide.guideText()
210
+ expect(text).toContain('安装应用')
211
+ expect(text).toContain('⋮')
212
+ expect(text).toContain('添加到主屏幕')
213
+ })
214
+
215
+ it('other browsers get the switch-to-Chrome/Safari guidance', () => {
216
+ const guide = runInstallGuide({ ua: UA.desktopFirefox })
217
+ guide.findBtn()?.onclick?.()
218
+ const text = guide.guideText()
219
+ expect(text).toContain('Chrome')
220
+ expect(text).toContain('Safari')
221
+ })
222
+
223
+ it('知道了 closes the overlay AND dismisses the floating entry persistently', () => {
224
+ const guide = runInstallGuide({ ua: UA.desktopFirefox })
225
+ guide.findBtn()?.onclick?.()
226
+ const overlay = guide.findGuide()
227
+ expect(overlay).toBeDefined()
228
+ const ok = overlay?.children[0]?.children.find(child => child.tagName === 'button')
229
+ ok?.onclick?.()
230
+ expect(guide.findGuide()).toBeUndefined()
231
+ expect(guide.findBtn()).toBeUndefined()
232
+ expect(guide.findClose()).toBeUndefined()
233
+ expect(guide.storage.get('dsh-bridge-pwa-dismissed')).toBe('1')
234
+ })
235
+
236
+ it('a persisted dismissed flag hides the entry on later loads', () => {
237
+ const guide = runInstallGuide({ ua: UA.androidChrome, dismissed: true })
238
+ expect(guide.findBtn()).toBeUndefined()
239
+ expect(guide.findClose()).toBeUndefined()
240
+ })
241
+
242
+ it('after dismissal a later beforeinstallprompt does not recreate the button', () => {
243
+ const guide = runInstallGuide({ ua: UA.androidChrome })
244
+ guide.findBtn()?.onclick?.()
245
+ guide.findGuide()?.children[0]?.children.find(child => child.tagName === 'button')?.onclick?.()
246
+ expect(guide.findBtn()).toBeUndefined()
247
+ guide.fire('beforeinstallprompt', { preventDefault: () => {}, prompt: () => {}, userChoice: Promise.resolve({ outcome: 'accepted' }) })
248
+ expect(guide.findBtn()).toBeUndefined()
249
+ expect(guide.findGuide()).toBeUndefined()
250
+ })
251
+
252
+ it('after dismissal DOMContentLoaded does not recreate the button', () => {
253
+ const guide = runInstallGuide({ ua: UA.androidChrome, dismissed: true, bodyReady: false })
254
+ guide.domReady()
255
+ expect(guide.findBtn()).toBeUndefined()
256
+ })
257
+
258
+ it('the × close affordance dismisses the entry without opening the guide', () => {
259
+ const guide = runInstallGuide({ ua: UA.androidChrome })
260
+ const close = guide.findClose()
261
+ expect(close).toBeDefined()
262
+ expect(close?.textContent).toBe('×')
263
+ close?.onclick?.({ stopPropagation: () => {} })
264
+ expect(guide.findBtn()).toBeUndefined()
265
+ expect(guide.findClose()).toBeUndefined()
266
+ expect(guide.findGuide()).toBeUndefined()
267
+ expect(guide.storage.get('dsh-bridge-pwa-dismissed')).toBe('1')
268
+ })
269
+
270
+ it('clicking the overlay backdrop dismisses the entry', () => {
271
+ const guide = runInstallGuide({ ua: UA.androidChrome })
272
+ guide.findBtn()?.onclick?.()
273
+ const overlay = guide.findGuide()
274
+ expect(overlay).toBeDefined()
275
+ overlay?.onclick?.({ target: overlay })
276
+ expect(guide.findGuide()).toBeUndefined()
277
+ expect(guide.findBtn()).toBeUndefined()
278
+ expect(guide.storage.get('dsh-bridge-pwa-dismissed')).toBe('1')
279
+ })
280
+
281
+ it('clicking inside the guide card does not dismiss', () => {
282
+ const guide = runInstallGuide({ ua: UA.androidChrome })
283
+ guide.findBtn()?.onclick?.()
284
+ const overlay = guide.findGuide()
285
+ const card = overlay?.children[0]
286
+ overlay?.onclick?.({ target: card })
287
+ expect(guide.findGuide()).toBeDefined()
288
+ expect(guide.findBtn()).toBeDefined()
289
+ expect(guide.storage.get('dsh-bridge-pwa-dismissed')).toBeUndefined()
290
+ })
291
+
292
+ it('the guide says installation stays available from the browser menu', () => {
293
+ const guide = runInstallGuide({ ua: UA.androidChrome })
294
+ guide.findBtn()?.onclick?.()
295
+ expect(guide.guideText()).toContain('浏览器菜单')
296
+ expect(guide.guideText()).toContain('不再显示此按钮')
297
+ })
298
+
299
+ it('standalone display mode hides the entry entirely', () => {
300
+ const guide = runInstallGuide({ ua: UA.androidChrome, standalone: true })
301
+ expect(guide.findBtn()).toBeUndefined()
302
+ })
303
+
304
+ it('iOS navigator.standalone hides the entry entirely', () => {
305
+ const guide = runInstallGuide({ ua: UA.iphoneSafari, iosStandalone: true })
306
+ expect(guide.findBtn()).toBeUndefined()
307
+ })
308
+
309
+ it('a persisted installed flag hides the entry on later loads', () => {
310
+ const guide = runInstallGuide({ ua: UA.androidChrome, installed: true })
311
+ expect(guide.findBtn()).toBeUndefined()
312
+ })
313
+
314
+ it('a captured beforeinstallprompt installs in one tap without the overlay', async () => {
315
+ const guide = runInstallGuide({ ua: UA.androidChrome })
316
+ let prompted = 0
317
+ let prevented = 0
318
+ guide.fire('beforeinstallprompt', {
319
+ preventDefault: () => { prevented += 1 },
320
+ prompt: () => { prompted += 1 },
321
+ userChoice: Promise.resolve({ outcome: 'accepted' }),
322
+ })
323
+ expect(prevented).toBe(1)
324
+ guide.findBtn()?.onclick?.()
325
+ expect(prompted).toBe(1)
326
+ expect(guide.findGuide()).toBeUndefined()
327
+ await flush()
328
+ expect(guide.findBtn()).toBeUndefined()
329
+ expect(guide.storage.get('dsh-bridge-pwa-installed')).toBe('1')
330
+ })
331
+
332
+ it('a dismissed prompt keeps the button for a retry', async () => {
333
+ const guide = runInstallGuide({ ua: UA.androidChrome })
334
+ guide.fire('beforeinstallprompt', {
335
+ preventDefault: () => {},
336
+ prompt: () => {},
337
+ userChoice: Promise.resolve({ outcome: 'dismissed' }),
338
+ })
339
+ guide.findBtn()?.onclick?.()
340
+ await flush()
341
+ expect(guide.findBtn()).toBeDefined()
342
+ })
343
+
344
+ it('appinstalled hides the button and persists the installed flag', () => {
345
+ const guide = runInstallGuide({ ua: UA.androidChrome })
346
+ expect(guide.findBtn()).toBeDefined()
347
+ guide.fire('appinstalled', undefined)
348
+ expect(guide.findBtn()).toBeUndefined()
349
+ expect(guide.storage.get('dsh-bridge-pwa-installed')).toBe('1')
350
+ const reload = runInstallGuide({ ua: UA.androidChrome, installed: true })
351
+ expect(reload.findBtn()).toBeUndefined()
352
+ })
353
+ })
354
+
355
+ // ---------------------------------------------------------------------------
356
+ // Service-worker decrypted-asset CacheStorage behavior (vm).
357
+ // The SW is run verbatim against a mock CacheStorage + auto-opening WebSocket;
358
+ // the test plays the blind relay peer, decrypting each request frame and
359
+ // encrypting a response frame with the same pair key the SW derives.
360
+ // ---------------------------------------------------------------------------
361
+
362
+ const te = new TextEncoder()
363
+ const td = new TextDecoder()
364
+ function toB64(bytes: Uint8Array): string { let s = ''; for (const b of bytes) s += String.fromCharCode(b); return btoa(s) }
365
+ function fromB64(value: string): Uint8Array { const raw = atob(value); const out = new Uint8Array(raw.length); for (let i = 0; i < raw.length; i += 1) out[i] = raw.charCodeAt(i); return out }
366
+ async function peerKey(pair: { k?: string; s: string }): Promise<CryptoKey> {
367
+ const material = await webcrypto.subtle.importKey('raw', te.encode('dsh-mobile-bridge/v1:' + (pair.k ?? '') + ':' + pair.s), 'HKDF', false, ['deriveKey'])
368
+ return webcrypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: te.encode('dsh-mobile-bridge'), info: new Uint8Array(0) }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
369
+ }
370
+ async function peerEncrypt(key: CryptoKey, value: unknown): Promise<string> {
371
+ const nonce = webcrypto.getRandomValues(new Uint8Array(12))
372
+ const ct = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, key, te.encode(JSON.stringify(value)))
373
+ const out = new Uint8Array(12 + ct.byteLength); out.set(nonce, 0); out.set(new Uint8Array(ct), 12)
374
+ return toB64(out)
375
+ }
376
+ async function peerDecrypt(key: CryptoKey, blob: string): Promise<any> {
377
+ const raw = fromB64(blob)
378
+ const pt = await webcrypto.subtle.decrypt({ name: 'AES-GCM', iv: raw.slice(0, 12) }, key, raw.slice(12))
379
+ return JSON.parse(td.decode(pt))
380
+ }
381
+ async function bucketName(pair: { k?: string; s: string }): Promise<string> {
382
+ const digest = await webcrypto.subtle.digest('SHA-256', te.encode('dsh-mobile-bridge/assets/v1:' + (pair.k ?? '') + ':' + pair.s))
383
+ return 'dshmb-assets-' + Array.from(new Uint8Array(digest)).slice(0, 8).map(b => b.toString(16).padStart(2, '0')).join('')
384
+ }
385
+ const textFrame = (text: string, type = 'text/javascript') => ({ status: 200, headers: { 'content-type': type }, body: toB64(te.encode(text)) })
386
+
387
+ type SwSocket = { url: string; sent: string[]; onopen: (() => void) | null; onerror: (() => void) | null; onclose: ((event: { code: number }) => void) | null; onmessage: ((event: { data: string }) => void) | null; send(data: string): void; close(code?: number, reason?: string): void }
388
+ type SwEnv = ReturnType<typeof makeSwEnv>
389
+
390
+ function makeSwEnv() {
391
+ const stores = new Map<string, Map<string, Response>>()
392
+ const cacheLog = { put: [] as Array<{ name: string; key: string }>, deleted: [] as string[], opened: [] as string[] }
393
+ const caches = {
394
+ async open(name: string) {
395
+ cacheLog.opened.push(name)
396
+ if (!stores.has(name)) stores.set(name, new Map())
397
+ const store = stores.get(name)!
398
+ return {
399
+ async match(key: string) { const hit = store.get(key); return hit ? hit.clone() : undefined },
400
+ async put(key: string, response: Response) { store.set(key, response.clone()); cacheLog.put.push({ name, key }) },
401
+ }
402
+ },
403
+ async keys() { return [...stores.keys()] },
404
+ async delete(name: string) { cacheLog.deleted.push(name); return stores.delete(name) },
405
+ }
406
+ const handlers: Record<string, Array<(event: any) => void>> = {}
407
+ const sockets: SwSocket[] = []
408
+ const frames: Array<{ socket: SwSocket; data: string }> = []
409
+ const errors: string[] = []
410
+ const timers = new Map<number, { fn: () => void; ms: number }>()
411
+ let timerSeq = 0
412
+ const fakeSetTimeout = (fn: () => void, ms: number) => { const id = ++timerSeq; timers.set(id, { fn, ms }); return id }
413
+ const fakeClearTimeout = (id: number) => { timers.delete(id) }
414
+ const env = {
415
+ stores, cacheLog, sockets, frames, errors, handlers, timers,
416
+ pair: { k: 'passphrase', s: 'pair-secret-A' } as { k?: string; s: string; streamOpenTimeoutMs?: number },
417
+ sentCount: () => frames.length,
418
+ lastSocket: () => sockets[sockets.length - 1],
419
+ fire: (name: string, event: any) => { for (const fn of handlers[name] ?? []) fn(event) },
420
+ sandbox: null as any,
421
+ }
422
+ class FakeWebSocket implements SwSocket {
423
+ url: string
424
+ sent: string[] = []
425
+ onopen: (() => void) | null = null
426
+ onerror: (() => void) | null = null
427
+ onclose: ((event: { code: number }) => void) | null = null
428
+ onmessage: ((event: { data: string }) => void) | null = null
429
+ constructor(url: string) { this.url = url; sockets.push(this); queueMicrotask(() => this.onopen?.()) }
430
+ send(data: string) { this.sent.push(data); frames.push({ socket: this, data }) }
431
+ close(code?: number) { this.onclose?.({ code: code ?? 1000 }) }
432
+ }
433
+ const selfStub = {
434
+ addEventListener: (name: string, fn: (event: any) => void) => { (handlers[name] ??= []).push(fn) },
435
+ skipWaiting: () => {},
436
+ clients: { claim: async () => {}, matchAll: async () => [] },
437
+ }
438
+ const sandbox: any = {
439
+ URL, Headers, Response, Request, TextEncoder, TextDecoder, Blob, Uint8Array, ArrayBuffer, ReadableStream, DecompressionStream,
440
+ crypto: webcrypto, btoa, atob, setTimeout: fakeSetTimeout, clearTimeout: fakeClearTimeout, queueMicrotask,
441
+ WebSocket: FakeWebSocket, caches, self: selfStub, location: { origin: 'https://relay.example' },
442
+ console: { error: (...a: unknown[]) => errors.push(a.map(String).join(' ')), info: () => {}, log: () => {}, warn: () => {} },
443
+ }
444
+ createContext(sandbox)
445
+ new Script(SW_SOURCE).runInContext(sandbox)
446
+ env.sandbox = sandbox
447
+ return env
448
+ }
449
+
450
+ const tick = () => new Promise(resolve => setTimeout(resolve, 0))
451
+
452
+ async function swPair(env: SwEnv, pair: { k?: string; s: string; streamOpenTimeoutMs?: number }) {
453
+ env.pair = pair
454
+ const waits: Array<Promise<unknown>> = []
455
+ const ready: unknown[] = []
456
+ env.fire('message', { data: { type: 'pair', pair }, ports: [{ postMessage: (m: unknown) => ready.push(m) }], waitUntil: (p: Promise<unknown>) => waits.push(p) })
457
+ await Promise.all(waits)
458
+ return ready
459
+ }
460
+
461
+ function swRequest(url: string, opts: { method?: string; accept?: string; mode?: string; cache?: string; range?: string } = {}) {
462
+ const headers = new Headers({ accept: opts.accept ?? '*/*' })
463
+ if (opts.range) headers.set('range', opts.range)
464
+ return { url, method: opts.method ?? 'GET', mode: opts.mode ?? 'cors', cache: opts.cache ?? 'default', headers, arrayBuffer: async () => new ArrayBuffer(0) }
465
+ }
466
+
467
+ /** Fire one fetch and play the relay peer until the response (and any background wait) settles. */
468
+ async function swFetch(env: SwEnv, request: ReturnType<typeof swRequest>, responder: (req: any) => { status: number; headers: Record<string, string>; body: string; compression?: string }) {
469
+ let response: Promise<Response> | undefined
470
+ const waits: Array<{ settled: boolean }> = []
471
+ let primarySettled = false
472
+ env.fire('fetch', {
473
+ request,
474
+ respondWith: (p: Promise<Response>) => { response = p; p.then(() => { primarySettled = true }, () => { primarySettled = true }) },
475
+ waitUntil: (p: Promise<unknown>) => { const w = { settled: false }; waits.push(w); p.then(() => { w.settled = true }, () => { w.settled = true }) },
476
+ })
477
+ const key = await peerKey(env.pair)
478
+ let fi = env.frames.length
479
+ let firstReq: any = null
480
+ for (let i = 0; i < 400; i += 1) {
481
+ await tick()
482
+ while (fi < env.frames.length) {
483
+ const { socket, data } = env.frames[fi]; fi += 1
484
+ const frame = JSON.parse(data)
485
+ const decoded = await peerDecrypt(key, frame.blob)
486
+ if (firstReq === null) firstReq = decoded
487
+ const blob = await peerEncrypt(key, responder(decoded))
488
+ socket.onmessage?.({ data: JSON.stringify({ id: frame.id, blob }) })
489
+ }
490
+ if (primarySettled && waits.every(w => w.settled)) break
491
+ }
492
+ if (!response) throw new Error('respondWith was not called')
493
+ const resolved = await response
494
+ return { response: resolved, req: firstReq }
495
+ }
496
+
497
+ describe('SW decrypted-asset CacheStorage (vm)', () => {
498
+ it('caches a decrypted static asset then serves the second load with zero network', async () => {
499
+ const env = makeSwEnv()
500
+ await swPair(env, env.pair)
501
+ const url = 'https://relay.example/assets/index-BxK3j9.js'
502
+ const first = await swFetch(env, swRequest(url), () => textFrame('console.log("asset-v1")'))
503
+ expect(first.req.path).toBe('/assets/index-BxK3j9.js')
504
+ expect(await first.response.text()).toContain('asset-v1')
505
+ const bucket = await bucketName(env.pair)
506
+ expect(env.cacheLog.put).toContainEqual({ name: bucket, key: url })
507
+ const sentAfterFirst = env.sentCount()
508
+ const socketsAfterFirst = env.sockets.length
509
+ const second = await swFetch(env, swRequest(url), () => { throw new Error('cache hit must not reach the relay') })
510
+ expect(await second.response.text()).toContain('asset-v1')
511
+ expect(second.req).toBeNull()
512
+ expect(env.sentCount()).toBe(sentAfterFirst)
513
+ expect(env.sockets.length).toBe(socketsAfterFirst)
514
+ expect(env.errors).toEqual([])
515
+ })
516
+
517
+ it('never caches API GET or any POST', async () => {
518
+ const env = makeSwEnv()
519
+ await swPair(env, env.pair)
520
+ const api = await swFetch(env, swRequest('https://relay.example/api/me', { accept: 'application/json' }), () => textFrame('{"ok":true}', 'application/json'))
521
+ expect(api.req.path).toBe('/api/me')
522
+ await swFetch(env, swRequest('https://relay.example/api/login/bridge', { method: 'POST', accept: 'application/json' }), () => textFrame('{"ok":true}', 'application/json'))
523
+ expect(env.cacheLog.put.filter(entry => entry.name.startsWith('dshmb-assets-'))).toEqual([])
524
+ expect(env.sentCount()).toBe(2)
525
+ })
526
+
527
+ it('does not cache non-200 or range responses', async () => {
528
+ const env = makeSwEnv()
529
+ await swPair(env, env.pair)
530
+ await swFetch(env, swRequest('https://relay.example/assets/missing.js'), () => ({ status: 404, headers: { 'content-type': 'text/plain' }, body: toB64(te.encode('nope')) }))
531
+ await swFetch(env, swRequest('https://relay.example/assets/big.js', { range: 'bytes=0-99' }), () => ({ status: 206, headers: { 'content-type': 'text/javascript' }, body: toB64(te.encode('partial')) }))
532
+ expect(env.cacheLog.put.filter(entry => entry.name.startsWith('dshmb-assets-'))).toEqual([])
533
+ })
534
+
535
+ it('pair-key rotation prunes the old bucket and re-fetches into a new one', async () => {
536
+ const env = makeSwEnv()
537
+ const pairA = { k: 'passphrase', s: 'pair-secret-A' }
538
+ const pairB = { k: 'passphrase', s: 'pair-secret-B' }
539
+ await swPair(env, pairA)
540
+ const url = 'https://relay.example/assets/index-BxK3j9.js'
541
+ await swFetch(env, swRequest(url), () => textFrame('asset-A'))
542
+ const bucketA = await bucketName(pairA)
543
+ const bucketB = await bucketName(pairB)
544
+ expect(bucketA).not.toBe(bucketB)
545
+ expect(env.stores.has(bucketA)).toBe(true)
546
+ await swPair(env, pairB)
547
+ expect(env.cacheLog.deleted).toContain(bucketA)
548
+ expect(env.stores.has(bucketA)).toBe(false)
549
+ const sentBefore = env.sentCount()
550
+ const refetch = await swFetch(env, swRequest(url), () => textFrame('asset-B'))
551
+ expect(await refetch.response.text()).toContain('asset-B')
552
+ expect(env.sentCount()).toBeGreaterThan(sentBefore)
553
+ expect(env.cacheLog.put).toContainEqual({ name: bucketB, key: url })
554
+ const hit = await swFetch(env, swRequest(url), () => { throw new Error('rotated bucket hit must not reach the relay') })
555
+ expect(await hit.response.text()).toContain('asset-B')
556
+ })
557
+
558
+ it('un-versioned HTML shell is stale-while-revalidate: cached render + background refresh', async () => {
559
+ const env = makeSwEnv()
560
+ await swPair(env, env.pair)
561
+ const shell = () => swRequest('https://relay.example/', { mode: 'navigate', accept: 'text/html' })
562
+ const first = await swFetch(env, shell(), () => textFrame('<html><head></head><body>shell-v1</body></html>', 'text/html; charset=utf-8'))
563
+ expect(await first.response.text()).toContain('shell-v1')
564
+ const bucket = await bucketName(env.pair)
565
+ expect(env.cacheLog.put).toContainEqual({ name: bucket, key: 'https://relay.example/' })
566
+ const sentBefore = env.sentCount()
567
+ const second = await swFetch(env, shell(), () => textFrame('<html><head></head><body>shell-v2</body></html>', 'text/html; charset=utf-8'))
568
+ const rendered = await second.response.text()
569
+ expect(rendered).toContain('shell-v1')
570
+ expect(rendered).toContain('rel="manifest"')
571
+ expect(env.sentCount()).toBeGreaterThan(sentBefore)
572
+ const stored = env.stores.get(bucket)!.get('https://relay.example/')!
573
+ expect(await stored.text()).toContain('shell-v2')
574
+ })
575
+
576
+ it('versioned HTML shell is cache-first with no background round trip', async () => {
577
+ const env = makeSwEnv()
578
+ await swPair(env, env.pair)
579
+ const url = 'https://relay.example/index.html?rev=deadbeef'
580
+ const req = () => swRequest(url, { mode: 'navigate', accept: 'text/html' })
581
+ await swFetch(env, req(), () => textFrame('<html><head></head><body>rev-v1</body></html>', 'text/html; charset=utf-8'))
582
+ const sentBefore = env.sentCount()
583
+ const second = await swFetch(env, req(), () => { throw new Error('versioned shell hit must not revalidate') })
584
+ expect(await second.response.text()).toContain('rev-v1')
585
+ expect(env.sentCount()).toBe(sentBefore)
586
+ })
587
+
588
+ it('a revoked device is served the offline page, never the cached asset', async () => {
589
+ const env = makeSwEnv()
590
+ await swPair(env, env.pair)
591
+ const url = 'https://relay.example/assets/index-BxK3j9.js'
592
+ await swFetch(env, swRequest(url), () => textFrame('asset-v1'))
593
+ await swFetch(env, swRequest('https://relay.example/', { mode: 'navigate', accept: 'text/html' }), () => textFrame('<html><head></head><body>shell</body></html>', 'text/html; charset=utf-8'))
594
+ env.lastSocket().onclose?.({ code: 4003 })
595
+ await tick()
596
+ const sentBefore = env.sentCount()
597
+ const nav = await swFetch(env, swRequest('https://relay.example/', { mode: 'navigate', accept: 'text/html' }), () => { throw new Error('revoked must not relay') })
598
+ expect(await nav.response.text()).toContain('此设备已下线')
599
+ expect(env.sentCount()).toBe(sentBefore)
600
+ })
601
+
602
+ it('leaves /bridge, /sw.js and /ws on the network (respondWith not called)', () => {
603
+ const env = makeSwEnv()
604
+ let called = 0
605
+ for (const path of ['/bridge/client.js', '/sw.js', '/ws/client']) {
606
+ env.fire('fetch', { request: swRequest('https://relay.example' + path), respondWith: () => { called += 1 }, waitUntil: () => {} })
607
+ }
608
+ expect(called).toBe(0)
609
+ })
610
+ })
611
+
612
+ // ---------------------------------------------------------------------------
613
+ // Application-WS open-handshake timeout (slow mobile link resilience).
614
+ // ---------------------------------------------------------------------------
615
+
616
+ function swPort() {
617
+ const received: any[] = []
618
+ return {
619
+ received,
620
+ closed: false,
621
+ onmessage: null as any,
622
+ start() {},
623
+ postMessage(message: any) { received.push(message) },
624
+ close() { this.closed = true },
625
+ }
626
+ }
627
+
628
+ /** Fire an application-websocket open and pump until the open request frame hits the relay. */
629
+ async function swOpenFrame(env: SwEnv, command: Record<string, unknown>, port: ReturnType<typeof swPort>) {
630
+ env.fire('message', { data: { type: 'application-websocket', ...command }, ports: [port], waitUntil: () => {} })
631
+ const key = await peerKey(env.pair)
632
+ let frame: any = null
633
+ for (let i = 0; i < 200 && !frame; i += 1) {
634
+ await tick()
635
+ const last = env.frames[env.frames.length - 1]
636
+ if (last) frame = JSON.parse(last.data)
637
+ }
638
+ if (!frame) throw new Error('open frame was never sent')
639
+ const req = await peerDecrypt(key, frame.blob)
640
+ return { frame, req, key }
641
+ }
642
+
643
+ describe('SW application-WS open timeout (vm)', () => {
644
+ it('defaults the open handshake to 15s and clears the timer once opened', async () => {
645
+ const env = makeSwEnv()
646
+ await swPair(env, env.pair)
647
+ const port = swPort()
648
+ const { frame, req, key } = await swOpenFrame(env, { path: '/ws/session', protocols: [] }, port)
649
+ expect(req.kind).toBe('websocket-open')
650
+ expect([...env.timers.values()].some(timer => timer.ms === 15000)).toBe(true)
651
+ const blob = await peerEncrypt(key, { kind: 'websocket-open', protocol: '' })
652
+ env.lastSocket().onmessage?.({ data: JSON.stringify({ id: frame.id, blob }) })
653
+ await tick(); await tick()
654
+ expect(port.received).toContainEqual({ kind: 'websocket-open', protocol: '' })
655
+ expect(env.timers.size).toBe(0)
656
+ expect(env.errors).toEqual([])
657
+ })
658
+
659
+ it('honors a pair-configured timeout', async () => {
660
+ const env = makeSwEnv()
661
+ await swPair(env, { k: 'passphrase', s: 'pair-secret-A', streamOpenTimeoutMs: 20000 })
662
+ const port = swPort()
663
+ await swOpenFrame(env, { path: '/ws/session', protocols: [] }, port)
664
+ expect([...env.timers.values()].some(timer => timer.ms === 20000)).toBe(true)
665
+ })
666
+
667
+ it('lets the page localStorage override win over pair config', async () => {
668
+ const env = makeSwEnv()
669
+ await swPair(env, { k: 'passphrase', s: 'pair-secret-A', streamOpenTimeoutMs: 20000 })
670
+ const port = swPort()
671
+ await swOpenFrame(env, { path: '/ws/session', protocols: [], streamOpenTimeoutMs: 25000 }, port)
672
+ expect([...env.timers.values()].some(timer => timer.ms === 25000)).toBe(true)
673
+ })
674
+
675
+ it('falls back to 15s for invalid or out-of-range config', async () => {
676
+ const env = makeSwEnv()
677
+ await swPair(env, env.pair)
678
+ const port = swPort()
679
+ await swOpenFrame(env, { path: '/ws/session', protocols: [], streamOpenTimeoutMs: 500 }, port)
680
+ expect([...env.timers.values()].some(timer => timer.ms === 15000)).toBe(true)
681
+ })
682
+
683
+ it('a stalled open fails fast with websocket-error so the app can retry', async () => {
684
+ const env = makeSwEnv()
685
+ await swPair(env, { k: 'passphrase', s: 'pair-secret-A', streamOpenTimeoutMs: 1000 })
686
+ const port = swPort()
687
+ await swOpenFrame(env, { path: '/ws/session', protocols: [] }, port)
688
+ const timer = [...env.timers.values()].find(candidate => candidate.ms === 1000)
689
+ expect(timer).toBeDefined()
690
+ timer!.fn()
691
+ expect(port.received).toContainEqual({ kind: 'websocket-error', message: 'stream open timed out' })
692
+ expect(port.closed).toBe(true)
693
+ expect(env.timers.size).toBe(0)
694
+ })
695
+ })
696
+
697
+ describe('socket-client facade open-timeout config (vm)', () => {
698
+ function runFacade(storage: Record<string, string>) {
699
+ const posted: any[] = []
700
+ const map = new Map(Object.entries(storage))
701
+ class FakeChannel { port1 = { onmessage: null as any, start() {}, postMessage() {}, close() {} }; port2 = {} }
702
+ const sandbox: any = {
703
+ URL, EventTarget, DOMException, Blob, ArrayBuffer, Uint8Array, btoa, atob,
704
+ MessageChannel: FakeChannel,
705
+ Event: class {}, MessageEvent: class {}, CloseEvent: class {}, ErrorEvent: class {},
706
+ location: { href: 'https://relay.example/', protocol: 'https:', host: 'relay.example', origin: 'https://relay.example' },
707
+ navigator: { serviceWorker: { controller: { postMessage: (message: any) => posted.push(message) } } },
708
+ localStorage: { getItem: (key: string) => map.get(key) ?? null, setItem: (key: string, value: string) => map.set(key, value) },
709
+ console: { info: () => {}, error: () => {} },
710
+ }
711
+ createContext(sandbox)
712
+ new Script(SOCKET_CLIENT_SOURCE).runInContext(sandbox)
713
+ return { sandbox, posted }
714
+ }
715
+
716
+ it('passes a localStorage open-timeout override to the SW', () => {
717
+ const { sandbox, posted } = runFacade({ 'dshmb-stream-open-timeout-ms': '25000' })
718
+ new sandbox.WebSocket('wss://relay.example/ws/session')
719
+ expect(posted[0].type).toBe('application-websocket')
720
+ expect(posted[0].streamOpenTimeoutMs).toBe(25000)
721
+ })
722
+
723
+ it('omits the override when localStorage has no valid value', () => {
724
+ const { sandbox, posted } = runFacade({ 'dshmb-stream-open-timeout-ms': 'not-a-number' })
725
+ new sandbox.WebSocket('wss://relay.example/ws/session')
726
+ expect(posted[0].streamOpenTimeoutMs).toBeUndefined()
727
+ })
728
+ })