@sparkelf/dsh-mobile-bridge-server 0.2.7 → 0.2.9
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 +7 -3
- package/src/assets/icon-192.png +0 -0
- package/src/assets/icon-512.png +0 -0
- package/src/assets/icon-maskable-512.png +0 -0
- package/src/index.ts +0 -0
- package/src/phone.ts +54 -2
- package/src/pwa.spec.ts +63 -0
- package/src/server.ts +64 -9
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.9",
|
|
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",
|
|
@@ -21,7 +21,11 @@
|
|
|
21
21
|
"QR_SCANNER_LICENSE",
|
|
22
22
|
"THIRD_PARTY_NOTICES.md",
|
|
23
23
|
"ZXING_CPP_LICENSE",
|
|
24
|
-
"ZXING_WASM_LICENSE"
|
|
24
|
+
"ZXING_WASM_LICENSE",
|
|
25
|
+
"src/assets/icon-192.png",
|
|
26
|
+
"src/assets/icon-512.png",
|
|
27
|
+
"src/assets/icon-maskable-512.png",
|
|
28
|
+
"src/pwa.spec.ts"
|
|
25
29
|
],
|
|
26
30
|
"dependencies": {
|
|
27
31
|
"nodemailer": "9.0.5",
|
|
@@ -29,4 +33,4 @@
|
|
|
29
33
|
"ws": "^8.18.0",
|
|
30
34
|
"zxing-wasm": "3.1.3"
|
|
31
35
|
}
|
|
32
|
-
}
|
|
36
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/src/index.ts
CHANGED
|
File without changes
|
package/src/phone.ts
CHANGED
|
@@ -26,6 +26,57 @@ async function decryptJSON(key, blob) {
|
|
|
26
26
|
}
|
|
27
27
|
`
|
|
28
28
|
|
|
29
|
+
/** PWA head fragments injected into every relayed HTML document. */
|
|
30
|
+
export const PWA_HEAD = '<link rel="manifest" href="/bridge/manifest.webmanifest"><meta name="theme-color" content="#0d1015"><link rel="apple-touch-icon" href="/bridge/icon-192.png"><script src="/bridge/pwa-install.js"></script>'
|
|
31
|
+
|
|
32
|
+
/** Web app manifest for the phone companion; scope stays under /bridge/. */
|
|
33
|
+
export const PWA_MANIFEST = JSON.stringify({
|
|
34
|
+
name: 'DeepSeek Harness',
|
|
35
|
+
short_name: 'DSH',
|
|
36
|
+
start_url: '/bridge/',
|
|
37
|
+
scope: '/bridge/',
|
|
38
|
+
display: 'standalone',
|
|
39
|
+
background_color: '#0d1015',
|
|
40
|
+
theme_color: '#0d1015',
|
|
41
|
+
icons: [
|
|
42
|
+
{ src: '/bridge/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
|
|
43
|
+
{ src: '/bridge/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
|
|
44
|
+
{ src: '/bridge/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
|
|
45
|
+
],
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
/** One-tap install guide: captures beforeinstallprompt; iOS gets a share-sheet hint once. */
|
|
49
|
+
export const PWA_INSTALL_SOURCE = `/* DSH mobile bridge PWA install guide. */
|
|
50
|
+
(function () {
|
|
51
|
+
if (window.matchMedia('(display-mode: standalone)').matches || navigator.standalone) return
|
|
52
|
+
var deferred = null
|
|
53
|
+
var btn = null
|
|
54
|
+
function ensureBtn() {
|
|
55
|
+
if (btn) return btn
|
|
56
|
+
btn = document.createElement('button')
|
|
57
|
+
btn.textContent = '安装到主屏幕'
|
|
58
|
+
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
|
+
btn.onclick = function () {
|
|
60
|
+
if (deferred) { deferred.prompt(); deferred.userChoice.then(function () { deferred = null; if (btn) { btn.remove(); btn = null } }) }
|
|
61
|
+
else showIos()
|
|
62
|
+
}
|
|
63
|
+
document.body.appendChild(btn)
|
|
64
|
+
return btn
|
|
65
|
+
}
|
|
66
|
+
function showIos() {
|
|
67
|
+
var ov = document.createElement('div')
|
|
68
|
+
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') }
|
|
71
|
+
document.body.appendChild(ov)
|
|
72
|
+
}
|
|
73
|
+
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)
|
|
77
|
+
})()
|
|
78
|
+
`
|
|
79
|
+
|
|
29
80
|
export const SW_SOURCE = `/* DSH mobile bridge service worker: blind-server E2EE client. */
|
|
30
81
|
${CRYPTO_JS}
|
|
31
82
|
let pairValue = null
|
|
@@ -161,7 +212,8 @@ function wsReady() {
|
|
|
161
212
|
}
|
|
162
213
|
if ((full.headers?.['content-type'] ?? '').includes('text/html')) {
|
|
163
214
|
let html = new TextDecoder().decode(body)
|
|
164
|
-
if (!html.includes('/bridge/socket-client.js')) html = html.replace('</head>', '<script src="/bridge/socket-client.js"></script></head>')
|
|
215
|
+
if (!html.includes('/bridge/socket-client.js')) html = html.replace('</head>', PWA_HEAD + '<script src="/bridge/socket-client.js"></script></head>')
|
|
216
|
+
else if (!html.includes('/bridge/manifest.webmanifest')) html = html.replace('</head>', PWA_HEAD + '</head>')
|
|
165
217
|
body = new TextEncoder().encode(html)
|
|
166
218
|
}
|
|
167
219
|
pending.delete(frame.id)
|
|
@@ -476,7 +528,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
476
528
|
|
|
477
529
|
function registerSw(pair) {
|
|
478
530
|
if (!('serviceWorker' in navigator)) return Promise.reject(new Error('serviceWorkerUnsupported'))
|
|
479
|
-
return navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none' })
|
|
531
|
+
return navigator.serviceWorker.register('/bridge/sw.js', { scope: '/bridge/', updateViaCache: 'none' })
|
|
480
532
|
.then(activateLatestWorker)
|
|
481
533
|
.then(function () { return navigator.serviceWorker.ready })
|
|
482
534
|
.then(function (registration) { return persistPair(registration, pair) })
|
package/src/pwa.spec.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest'
|
|
2
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import type { AddressInfo } from 'node:net'
|
|
6
|
+
import { createBridgeServer } from './server.ts'
|
|
7
|
+
import { UserStore } from './store.ts'
|
|
8
|
+
import { CLIENT_SOURCE, PWA_HEAD } from './phone.ts'
|
|
9
|
+
|
|
10
|
+
const open: Array<{ close: () => void }> = []
|
|
11
|
+
afterEach(() => { for (const entry of open.splice(0)) entry.close() })
|
|
12
|
+
|
|
13
|
+
/** Start the real server on an ephemeral port. */
|
|
14
|
+
const startServer = async () => {
|
|
15
|
+
const dir = mkdtempSync(join(tmpdir(), 'bridge-pwa-'))
|
|
16
|
+
const store = new UserStore(join(dir, 'users.json'), 'test-secret-at-least-16-chars')
|
|
17
|
+
const server = createBridgeServer(store, {})
|
|
18
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
|
|
19
|
+
const port = (server.address() as AddressInfo).port
|
|
20
|
+
open.push({ close: () => { server.close(); rmSync(dir, { recursive: true, force: true }) } })
|
|
21
|
+
return 'http://127.0.0.1:' + String(port)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe('phone PWA install surface', () => {
|
|
25
|
+
it('serves a /bridge/-scoped manifest with install icons', async () => {
|
|
26
|
+
const base = await startServer()
|
|
27
|
+
const res = await fetch(base + '/bridge/manifest.webmanifest')
|
|
28
|
+
expect(res.status).toBe(200)
|
|
29
|
+
expect(res.headers.get('content-type')).toContain('application/manifest+json')
|
|
30
|
+
const manifest = JSON.parse(await res.text()) as Record<string, unknown>
|
|
31
|
+
expect(manifest.start_url).toBe('/bridge/')
|
|
32
|
+
expect(manifest.scope).toBe('/bridge/')
|
|
33
|
+
expect(manifest.display).toBe('standalone')
|
|
34
|
+
expect((manifest.icons as Array<{ sizes: string }>).map(icon => icon.sizes)).toEqual(['192x192', '512x512', '512x512'])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('serves the service worker under the /bridge/ scope and the install guide', async () => {
|
|
38
|
+
const base = await startServer()
|
|
39
|
+
const sw = await fetch(base + '/bridge/sw.js')
|
|
40
|
+
expect(sw.status).toBe(200)
|
|
41
|
+
expect(sw.headers.get('service-worker-allowed')).toBe('/bridge/')
|
|
42
|
+
const guide = await fetch(base + '/bridge/pwa-install.js')
|
|
43
|
+
expect(guide.status).toBe(200)
|
|
44
|
+
expect(await guide.text()).toContain('beforeinstallprompt')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('serves png icons for manifest and apple-touch-icon', async () => {
|
|
48
|
+
const base = await startServer()
|
|
49
|
+
for (const name of ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png']) {
|
|
50
|
+
const res = await fetch(base + '/bridge/' + name)
|
|
51
|
+
expect(res.status).toBe(200)
|
|
52
|
+
expect(res.headers.get('content-type')).toBe('image/png')
|
|
53
|
+
expect((await res.arrayBuffer()).byteLength).toBeGreaterThan(100)
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('injects manifest/theme/apple-touch/install-guide into relayed HTML heads', () => {
|
|
58
|
+
expect(PWA_HEAD).toContain('rel="manifest" href="/bridge/manifest.webmanifest"')
|
|
59
|
+
expect(PWA_HEAD).toContain('rel="apple-touch-icon"')
|
|
60
|
+
expect(PWA_HEAD).toContain('/bridge/pwa-install.js')
|
|
61
|
+
expect(CLIENT_SOURCE).toContain("register('/bridge/sw.js', { scope: '/bridge/'")
|
|
62
|
+
})
|
|
63
|
+
})
|
package/src/server.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { createRequire } from 'node:module'
|
|
|
14
14
|
import { dirname, resolve } from 'node:path'
|
|
15
15
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
16
16
|
import { WebSocket, WebSocketServer, type RawData } from 'ws'
|
|
17
|
-
import { SW_SOURCE, CLIENT_SOURCE, SOCKET_CLIENT_SOURCE } from './phone.ts'
|
|
17
|
+
import { SW_SOURCE, CLIENT_SOURCE, SOCKET_CLIENT_SOURCE, PWA_MANIFEST, PWA_INSTALL_SOURCE } from './phone.ts'
|
|
18
18
|
import { UserStore, type DeviceRecord } from './store.ts'
|
|
19
19
|
import type { WechatConfig } from './wechat.ts'
|
|
20
20
|
import { generateScheme } from './wechat-scheme.ts'
|
|
@@ -174,6 +174,36 @@ function requestIp(req: IncomingMessage): string {
|
|
|
174
174
|
return value?.trim() || req.socket.remoteAddress || 'unknown'
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
/**
|
|
178
|
+
* Whether one request reached this server over TLS.
|
|
179
|
+
*
|
|
180
|
+
* The session cookie carries `Secure` only when it does, because a browser refuses to store or send
|
|
181
|
+
* a `Secure` cookie over plain HTTP. The phone service worker authenticates its relay socket from
|
|
182
|
+
* that cookie alone -- it opens `/ws/client` without a token -- so a deployment served over HTTP
|
|
183
|
+
* without this check lost the cookie, and the phone could not authenticate its socket at all.
|
|
184
|
+
* @param req - Request whose scheme to classify.
|
|
185
|
+
* @returns True when the client used HTTPS.
|
|
186
|
+
*/
|
|
187
|
+
function requestIsSecure(req: IncomingMessage): boolean {
|
|
188
|
+
const forwarded = req.headers['x-forwarded-proto']
|
|
189
|
+
const value = Array.isArray(forwarded) ? forwarded[0] : forwarded?.split(',')[0]
|
|
190
|
+
if (value !== undefined && value.trim() !== '') return value.trim() === 'https'
|
|
191
|
+
return (req.socket as { encrypted?: boolean }).encrypted === true
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Session cookie attributes, with `Secure` only where a browser can return the cookie.
|
|
196
|
+
* @param req - Request the cookie answers.
|
|
197
|
+
* @param token - Session token to store.
|
|
198
|
+
* @param days - Lifetime in days.
|
|
199
|
+
* @returns The `Set-Cookie` value.
|
|
200
|
+
*/
|
|
201
|
+
function sessionCookie(req: IncomingMessage, token: string, days: number): string {
|
|
202
|
+
return COOKIE + '=' + encodeURIComponent(token)
|
|
203
|
+
+ '; HttpOnly; SameSite=Lax; Path=/; Max-Age=' + String(days * 86400)
|
|
204
|
+
+ (requestIsSecure(req) ? '; Secure' : '')
|
|
205
|
+
}
|
|
206
|
+
|
|
177
207
|
function requestDeviceName(req: IncomingMessage): string {
|
|
178
208
|
const userAgent = req.headers['user-agent'] ?? ''
|
|
179
209
|
const platform = /iPad/u.test(userAgent)
|
|
@@ -319,10 +349,10 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
319
349
|
return { token, device }
|
|
320
350
|
}
|
|
321
351
|
|
|
322
|
-
const respondLogin = (res: ServerResponse, token: string, days: number): void => {
|
|
352
|
+
const respondLogin = (req: IncomingMessage, res: ServerResponse, token: string, days: number): void => {
|
|
323
353
|
res.writeHead(200, {
|
|
324
354
|
'content-type': 'application/json',
|
|
325
|
-
'set-cookie': [
|
|
355
|
+
'set-cookie': [sessionCookie(req, token, days)],
|
|
326
356
|
})
|
|
327
357
|
res.end(JSON.stringify({ token }))
|
|
328
358
|
}
|
|
@@ -380,6 +410,27 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
380
410
|
res.end(SW_SOURCE)
|
|
381
411
|
return
|
|
382
412
|
}
|
|
413
|
+
if (url.pathname === '/bridge/sw.js') {
|
|
414
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store', 'service-worker-allowed': '/bridge/' })
|
|
415
|
+
res.end(SW_SOURCE)
|
|
416
|
+
return
|
|
417
|
+
}
|
|
418
|
+
if (url.pathname === '/bridge/manifest.webmanifest') {
|
|
419
|
+
res.writeHead(200, { 'content-type': 'application/manifest+json; charset=utf-8', 'cache-control': 'no-store' })
|
|
420
|
+
res.end(PWA_MANIFEST)
|
|
421
|
+
return
|
|
422
|
+
}
|
|
423
|
+
if (url.pathname === '/bridge/pwa-install.js') {
|
|
424
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
425
|
+
res.end(PWA_INSTALL_SOURCE)
|
|
426
|
+
return
|
|
427
|
+
}
|
|
428
|
+
if (url.pathname === '/bridge/icon-192.png' || url.pathname === '/bridge/icon-512.png' || url.pathname === '/bridge/icon-maskable-512.png') {
|
|
429
|
+
const file = url.pathname.slice('/bridge/'.length)
|
|
430
|
+
res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'public, max-age=86400' })
|
|
431
|
+
res.end(readFileSync(new URL('./assets/' + file, import.meta.url)))
|
|
432
|
+
return
|
|
433
|
+
}
|
|
383
434
|
if (req.method === 'POST' && url.pathname === '/bridge/api/email/code') {
|
|
384
435
|
if (mailer === undefined) { json(res, 503, { error: 'email login not configured' }); return }
|
|
385
436
|
try {
|
|
@@ -409,7 +460,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
409
460
|
if (priorDevice === undefined) throw new Error('scan a desktop pairing QR first')
|
|
410
461
|
store.bindDevice(token, priorDevice.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice.id)
|
|
411
462
|
}
|
|
412
|
-
respondLogin(res, token, days)
|
|
463
|
+
respondLogin(req, res, token, days)
|
|
413
464
|
} catch (error) { fail(res, 401, 'email login failed', error) }
|
|
414
465
|
return
|
|
415
466
|
}
|
|
@@ -419,7 +470,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
419
470
|
const verify = externalAuth[provider]
|
|
420
471
|
if (verify === undefined) throw new Error('unknown provider')
|
|
421
472
|
const externalId = await verify(payload)
|
|
422
|
-
respondLogin(res, store.loginExternal(provider, externalId), DEFAULT_SESSION_DAYS)
|
|
473
|
+
respondLogin(req, res, store.loginExternal(provider, externalId), DEFAULT_SESSION_DAYS)
|
|
423
474
|
} catch (error) { fail(res, 401, 'external login failed', error) }
|
|
424
475
|
return
|
|
425
476
|
}
|
|
@@ -434,7 +485,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
434
485
|
return
|
|
435
486
|
}
|
|
436
487
|
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
437
|
-
respondLogin(res, token, ticket.sessionDays)
|
|
488
|
+
respondLogin(req, res, token, ticket.sessionDays)
|
|
438
489
|
} catch (error) { fail(res, 401, 'pairing login failed', error) }
|
|
439
490
|
return
|
|
440
491
|
}
|
|
@@ -445,7 +496,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
445
496
|
if (ticket.email2fa === undefined) throw new Error('no pending challenge')
|
|
446
497
|
store.consumeEmailCode(ticket.email2fa, emailCode)
|
|
447
498
|
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
448
|
-
respondLogin(res, token, ticket.sessionDays)
|
|
499
|
+
respondLogin(req, res, token, ticket.sessionDays)
|
|
449
500
|
} catch (error) { fail(res, 401, 'pairing verification failed', error) }
|
|
450
501
|
return
|
|
451
502
|
}
|
|
@@ -497,7 +548,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
497
548
|
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'paired', devices: deviceViews(ticket.bridgeId) }))
|
|
498
549
|
}
|
|
499
550
|
res.writeHead(302, {
|
|
500
|
-
'set-cookie': [
|
|
551
|
+
'set-cookie': [sessionCookie(req, token, days)],
|
|
501
552
|
location: '/',
|
|
502
553
|
})
|
|
503
554
|
res.end()
|
|
@@ -621,7 +672,11 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
621
672
|
const device = store.deviceFor(token)
|
|
622
673
|
const bridgeId = device?.bridgeId
|
|
623
674
|
if (device === undefined || bridgeId === undefined) {
|
|
624
|
-
|
|
675
|
+
// 4003 means the desktop revoked this device, and the phone treats it as terminal: it clears
|
|
676
|
+
// the pairing and stops reconnecting. A request that simply arrived without a usable session
|
|
677
|
+
// is not that, and reporting it as a revocation left a phone whose cookie was missing with a
|
|
678
|
+
// dead pairing it never got told to renew. 4004 keeps the two apart.
|
|
679
|
+
wss.handleUpgrade(req, socket, head, client => { client.close(4004, 'pairing required') })
|
|
625
680
|
return
|
|
626
681
|
}
|
|
627
682
|
if (bridges.get(bridgeId)?.readyState !== WebSocket.OPEN) {
|