@sparkelf/dsh-mobile-bridge-server 0.2.12 → 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 +1 -1
- package/src/phone.ts +181 -54
- package/src/pwa.spec.ts +448 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sparkelf/dsh-mobile-bridge-server",
|
|
3
|
-
"version": "0.2.
|
|
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
|
@@ -50,23 +50,32 @@ export const PWA_MANIFEST = JSON.stringify({
|
|
|
50
50
|
* shows on every relayed page without waiting for Chrome's engagement-gated
|
|
51
51
|
* beforeinstallprompt. A captured prompt installs in one tap; otherwise the
|
|
52
52
|
* button opens per-browser manual steps (iOS share sheet / Android ⋮ menu /
|
|
53
|
-
* switch-browser advice). Installing hides the button and
|
|
54
|
-
* it never returns;
|
|
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.
|
|
55
57
|
*/
|
|
56
58
|
export const PWA_INSTALL_SOURCE = `/* DSH mobile bridge PWA install guide. */
|
|
57
59
|
(function () {
|
|
58
60
|
var INSTALLED_KEY = 'dsh-bridge-pwa-installed'
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
|
62
66
|
}
|
|
63
|
-
if (
|
|
67
|
+
if (isHidden()) return
|
|
64
68
|
var deferred = null
|
|
65
69
|
var btn = null
|
|
66
|
-
|
|
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() }
|
|
67
76
|
function ensureBtn() {
|
|
68
77
|
if (btn) return btn
|
|
69
|
-
if (
|
|
78
|
+
if (isHidden()) return null
|
|
70
79
|
btn = document.createElement('button')
|
|
71
80
|
btn.id = 'dsh-pwa-install-btn'
|
|
72
81
|
btn.textContent = '安装到主屏幕'
|
|
@@ -76,12 +85,18 @@ export const PWA_INSTALL_SOURCE = `/* DSH mobile bridge PWA install guide. */
|
|
|
76
85
|
var promptEvent = deferred
|
|
77
86
|
deferred = null
|
|
78
87
|
promptEvent.prompt()
|
|
79
|
-
promptEvent.userChoice.then(function (choice) { if (choice && choice.outcome === 'accepted') hideBtn() })
|
|
88
|
+
promptEvent.userChoice.then(function (choice) { if (choice && choice.outcome === 'accepted') { persist(INSTALLED_KEY); hideBtn() } })
|
|
80
89
|
return
|
|
81
90
|
}
|
|
82
91
|
showGuide()
|
|
83
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() }
|
|
84
98
|
document.body.appendChild(btn)
|
|
99
|
+
document.body.appendChild(closeBtn)
|
|
85
100
|
return btn
|
|
86
101
|
}
|
|
87
102
|
function guideKind() {
|
|
@@ -115,14 +130,19 @@ export const PWA_INSTALL_SOURCE = `/* DSH mobile bridge PWA install guide. */
|
|
|
115
130
|
var body = document.createElement('p')
|
|
116
131
|
body.style.cssText = 'margin:0;white-space:pre-line'
|
|
117
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 = '关闭后不再显示此按钮;之后仍可随时在浏览器菜单中安装。'
|
|
118
136
|
var ok = document.createElement('button')
|
|
119
137
|
ok.textContent = '知道了'
|
|
120
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'
|
|
121
|
-
ok.onclick = function () { ov.remove() }
|
|
139
|
+
ok.onclick = function () { ov.remove(); dismiss() }
|
|
122
140
|
card.appendChild(heading)
|
|
123
141
|
card.appendChild(body)
|
|
142
|
+
card.appendChild(note)
|
|
124
143
|
card.appendChild(ok)
|
|
125
144
|
ov.appendChild(card)
|
|
145
|
+
ov.onclick = function (event) { if (event && event.target === ov) { ov.remove(); dismiss() } }
|
|
126
146
|
document.body.appendChild(ov)
|
|
127
147
|
}
|
|
128
148
|
window.addEventListener('beforeinstallprompt', function (e) { e.preventDefault(); deferred = e; ensureBtn() })
|
|
@@ -144,6 +164,46 @@ let keyPromise = null
|
|
|
144
164
|
let revoked = false
|
|
145
165
|
const PAIR_CACHE = 'dsh-mobile-bridge-pair-v1'
|
|
146
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
|
+
}
|
|
147
207
|
async function waitForPair() {
|
|
148
208
|
if (pairValue) return pairValue
|
|
149
209
|
const cache = await caches.open(PAIR_CACHE)
|
|
@@ -167,7 +227,7 @@ self.addEventListener('message', event => {
|
|
|
167
227
|
if (!revoked) {
|
|
168
228
|
const replacedError = new Error('pair replaced')
|
|
169
229
|
for (const entry of pending.values()) {
|
|
170
|
-
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() }
|
|
171
231
|
else if (entry.controller) entry.controller.error(replacedError)
|
|
172
232
|
else entry.reject(replacedError)
|
|
173
233
|
}
|
|
@@ -175,11 +235,14 @@ self.addEventListener('message', event => {
|
|
|
175
235
|
pending.clear()
|
|
176
236
|
pairValue = event.data.pair
|
|
177
237
|
keyPromise = null
|
|
238
|
+
assetCachePromise = null
|
|
178
239
|
revoked = false
|
|
179
240
|
for (const resolve of pairWaiters) resolve(pairValue)
|
|
180
241
|
pairWaiters = []
|
|
181
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' } })))
|
|
182
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) }))
|
|
183
246
|
return
|
|
184
247
|
}
|
|
185
248
|
if (event.data.type === 'application-websocket') {
|
|
@@ -222,6 +285,7 @@ function wsReady() {
|
|
|
222
285
|
const settlePending = () => {
|
|
223
286
|
for (const entry of pending.values()) {
|
|
224
287
|
if (entry.websocketPort) {
|
|
288
|
+
if (entry.openTimer != null) clearTimeout(entry.openTimer)
|
|
225
289
|
entry.websocketPort.postMessage({ kind: 'websocket-error', message: error.message })
|
|
226
290
|
entry.websocketPort.close()
|
|
227
291
|
} else if (entry.controller) {
|
|
@@ -233,6 +297,7 @@ function wsReady() {
|
|
|
233
297
|
if (event.code === 4003 && isCurrent) {
|
|
234
298
|
pairValue = null
|
|
235
299
|
keyPromise = null
|
|
300
|
+
assetCachePromise = null
|
|
236
301
|
revoked = true
|
|
237
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) })
|
|
238
303
|
void self.clients.matchAll({ type: 'window' })
|
|
@@ -250,6 +315,7 @@ function wsReady() {
|
|
|
250
315
|
if (!entry) return
|
|
251
316
|
if (entry.websocketPort) {
|
|
252
317
|
void decryptJSON(entry.key, frame.blob).then(payload => {
|
|
318
|
+
if (payload.kind === 'websocket-open' && entry.openTimer != null) { clearTimeout(entry.openTimer); entry.openTimer = null }
|
|
253
319
|
entry.websocketPort.postMessage(payload)
|
|
254
320
|
if (payload.kind === 'websocket-close') { entry.websocketPort.close(); pending.delete(frame.id) }
|
|
255
321
|
}).catch(error => {
|
|
@@ -276,21 +342,47 @@ function wsReady() {
|
|
|
276
342
|
body = new TextEncoder().encode(html)
|
|
277
343
|
}
|
|
278
344
|
pending.delete(frame.id)
|
|
279
|
-
|
|
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)
|
|
280
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) })
|
|
281
351
|
}
|
|
282
352
|
})
|
|
283
353
|
return wsPromise
|
|
284
354
|
}
|
|
285
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
|
+
|
|
286
369
|
async function openApplicationSocket(command, port) {
|
|
287
370
|
const pair = await waitForPair()
|
|
288
371
|
if (revoked) throw new Error('device revoked')
|
|
289
372
|
if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
|
|
290
373
|
const key = await keyPromise
|
|
291
|
-
const ws = await wsReady()
|
|
292
374
|
const id = 'w' + (++counter)
|
|
293
|
-
|
|
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))
|
|
294
386
|
port.onmessage = event => {
|
|
295
387
|
void (async () => {
|
|
296
388
|
const message = event.data
|
|
@@ -304,8 +396,14 @@ async function openApplicationSocket(command, port) {
|
|
|
304
396
|
})
|
|
305
397
|
}
|
|
306
398
|
port.start()
|
|
307
|
-
|
|
308
|
-
|
|
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
|
+
}
|
|
309
407
|
}
|
|
310
408
|
|
|
311
409
|
function revokedResponse() {
|
|
@@ -313,6 +411,49 @@ function revokedResponse() {
|
|
|
313
411
|
return new Response(html, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
314
412
|
}
|
|
315
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
|
+
|
|
316
457
|
self.addEventListener('fetch', event => {
|
|
317
458
|
const url = new URL(event.request.url)
|
|
318
459
|
if (url.pathname.startsWith('/bridge') || url.pathname === '/sw.js' || url.pathname.startsWith('/ws')) return
|
|
@@ -328,45 +469,26 @@ self.addEventListener('fetch', event => {
|
|
|
328
469
|
if (event.request.mode === 'navigate') return revokedResponse()
|
|
329
470
|
return new Promise(() => {})
|
|
330
471
|
}
|
|
331
|
-
if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
|
|
332
|
-
const key = await keyPromise
|
|
333
472
|
const request = event.request
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
if (revoked) return revokedResponse()
|
|
352
|
-
console.error('[dsh-mobile-bridge] bridge connection failed', error)
|
|
353
|
-
return new Response('Mobile Bridge connection failed', { status: 502 })
|
|
354
|
-
}
|
|
355
|
-
if ((request.headers.get('accept') ?? '').includes('text/event-stream')) {
|
|
356
|
-
return new Promise((resolve, reject) => {
|
|
357
|
-
let controller
|
|
358
|
-
const readable = new ReadableStream({
|
|
359
|
-
start(value) { controller = value },
|
|
360
|
-
cancel() { pending.delete(id) },
|
|
361
|
-
})
|
|
362
|
-
pending.set(id, { key, controller, resolve: () => resolve(new Response(readable, { headers: { 'content-type': 'text/event-stream' } })), reject, status: 200, headers: {} })
|
|
363
|
-
ws.send(JSON.stringify({ id, blob, streamHint: true }))
|
|
364
|
-
})
|
|
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
|
+
}
|
|
365
490
|
}
|
|
366
|
-
return
|
|
367
|
-
pending.set(id, { key, resolve, reject })
|
|
368
|
-
ws.send(JSON.stringify({ id, blob }))
|
|
369
|
-
})
|
|
491
|
+
return relayFetch(request, url, pair, plan, cache)
|
|
370
492
|
})())
|
|
371
493
|
})
|
|
372
494
|
`
|
|
@@ -422,7 +544,12 @@ export const SOCKET_CLIENT_SOURCE = `/* E2EE WebSocket facade for the relayed Ha
|
|
|
422
544
|
}
|
|
423
545
|
this._port.port1.start()
|
|
424
546
|
var protocolList = protocols === undefined ? [] : (Array.isArray(protocols) ? protocols : [protocols])
|
|
425
|
-
|
|
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])
|
|
426
553
|
}
|
|
427
554
|
_emit(event) {
|
|
428
555
|
this.dispatchEvent(event)
|
package/src/pwa.spec.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
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, PWA_INSTALL_SOURCE, SW_SOURCE } from './phone.ts'
|
|
9
|
+
import { CLIENT_SOURCE, PWA_HEAD, PWA_INSTALL_SOURCE, SOCKET_CLIENT_SOURCE, SW_SOURCE } from './phone.ts'
|
|
9
10
|
import { Script, createContext } from 'node:vm'
|
|
10
11
|
|
|
11
12
|
const open: Array<{ close: () => void }> = []
|
|
@@ -82,7 +83,7 @@ type StubElement = {
|
|
|
82
83
|
style: { cssText: string }
|
|
83
84
|
children: StubElement[]
|
|
84
85
|
parent: StubElement | null
|
|
85
|
-
onclick: (() => void) | null
|
|
86
|
+
onclick: ((event?: { target?: StubElement; stopPropagation?: () => void }) => void) | null
|
|
86
87
|
appendChild(child: StubElement): StubElement
|
|
87
88
|
remove(): void
|
|
88
89
|
}
|
|
@@ -114,11 +115,12 @@ const UA = {
|
|
|
114
115
|
}
|
|
115
116
|
|
|
116
117
|
/** Run the real install guide in a vm with a stub DOM; returns observation handles. */
|
|
117
|
-
function runInstallGuide(opts: { ua: string; standalone?: boolean; iosStandalone?: boolean; installed?: boolean; touchPoints?: number; bodyReady?: boolean }) {
|
|
118
|
+
function runInstallGuide(opts: { ua: string; standalone?: boolean; iosStandalone?: boolean; installed?: boolean; dismissed?: boolean; touchPoints?: number; bodyReady?: boolean }) {
|
|
118
119
|
const windowListeners = new Map<string, Array<(event: unknown) => void>>()
|
|
119
120
|
const docListeners = new Map<string, Array<() => void>>()
|
|
120
121
|
const storage = new Map<string, string>()
|
|
121
122
|
if (opts.installed) storage.set('dsh-bridge-pwa-installed', '1')
|
|
123
|
+
if (opts.dismissed) storage.set('dsh-bridge-pwa-dismissed', '1')
|
|
122
124
|
const body = makeElement('body')
|
|
123
125
|
const doc = {
|
|
124
126
|
body: opts.bodyReady === false ? null : body,
|
|
@@ -154,6 +156,7 @@ function runInstallGuide(opts: { ua: string; standalone?: boolean; iosStandalone
|
|
|
154
156
|
fire: (name: string, event: unknown) => { for (const fn of windowListeners.get(name) ?? []) fn(event) },
|
|
155
157
|
domReady: () => { doc.body = body; for (const fn of docListeners.get('DOMContentLoaded') ?? []) fn() },
|
|
156
158
|
findBtn: () => body.children.find(child => child.id === 'dsh-pwa-install-btn'),
|
|
159
|
+
findClose: () => body.children.find(child => child.id === 'dsh-pwa-install-close'),
|
|
157
160
|
findGuide: () => body.children.find(child => child.id === 'dsh-pwa-guide'),
|
|
158
161
|
guideText: () => { const guide = body.children.find(child => child.id === 'dsh-pwa-guide'); return guide ? textOf(guide) : '' },
|
|
159
162
|
}
|
|
@@ -217,7 +220,7 @@ describe('PWA install entry behavior (vm)', () => {
|
|
|
217
220
|
expect(text).toContain('Safari')
|
|
218
221
|
})
|
|
219
222
|
|
|
220
|
-
it('知道了 closes the
|
|
223
|
+
it('知道了 closes the overlay AND dismisses the floating entry persistently', () => {
|
|
221
224
|
const guide = runInstallGuide({ ua: UA.desktopFirefox })
|
|
222
225
|
guide.findBtn()?.onclick?.()
|
|
223
226
|
const overlay = guide.findGuide()
|
|
@@ -225,7 +228,72 @@ describe('PWA install entry behavior (vm)', () => {
|
|
|
225
228
|
const ok = overlay?.children[0]?.children.find(child => child.tagName === 'button')
|
|
226
229
|
ok?.onclick?.()
|
|
227
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()
|
|
228
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('不再显示此按钮')
|
|
229
297
|
})
|
|
230
298
|
|
|
231
299
|
it('standalone display mode hides the entry entirely', () => {
|
|
@@ -258,6 +326,7 @@ describe('PWA install entry behavior (vm)', () => {
|
|
|
258
326
|
expect(guide.findGuide()).toBeUndefined()
|
|
259
327
|
await flush()
|
|
260
328
|
expect(guide.findBtn()).toBeUndefined()
|
|
329
|
+
expect(guide.storage.get('dsh-bridge-pwa-installed')).toBe('1')
|
|
261
330
|
})
|
|
262
331
|
|
|
263
332
|
it('a dismissed prompt keeps the button for a retry', async () => {
|
|
@@ -282,3 +351,378 @@ describe('PWA install entry behavior (vm)', () => {
|
|
|
282
351
|
expect(reload.findBtn()).toBeUndefined()
|
|
283
352
|
})
|
|
284
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
|
+
})
|