@sparkelf/dsh-mobile-bridge-server 0.1.0 → 0.2.1
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/THIRD_PARTY_NOTICES.md +11 -0
- package/package.json +1 -1
- package/src/deepseek-logo.svg +22 -0
- package/src/phone.ts +377 -46
- package/src/server.ts +342 -84
- package/src/store.ts +132 -31
- package/src/live.spec.ts +0 -108
- package/src/server.spec.ts +0 -181
- package/src/store.spec.ts +0 -40
package/src/server.ts
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Multi-user bridge server: phones and desktops authenticate with email
|
|
3
3
|
* verification codes or WeChat and bind to a pairing code. The server is a
|
|
4
|
-
* BLIND forwarder:
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* BLIND payload forwarder: the server parses only outer device route ids;
|
|
5
|
+
* encrypted `blob` payloads stay opaque between the phone Service Worker and
|
|
6
|
+
* desktop plugin.
|
|
7
7
|
* Bridges dial OUT from the local network, so no inbound port is needed.
|
|
8
8
|
* @module @sparkelf/dsh-mobile-bridge-server/server
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { randomBytes } from 'node:crypto'
|
|
11
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
12
|
+
import { readFileSync } from 'node:fs'
|
|
12
13
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
13
14
|
import { WebSocket, WebSocketServer } from 'ws'
|
|
14
|
-
import { SW_SOURCE, CLIENT_SOURCE } from './phone.ts'
|
|
15
|
-
import { UserStore } from './store.ts'
|
|
15
|
+
import { SW_SOURCE, CLIENT_SOURCE, SOCKET_CLIENT_SOURCE } from './phone.ts'
|
|
16
|
+
import { UserStore, type DeviceRecord } from './store.ts'
|
|
16
17
|
import type { WechatConfig } from './wechat.ts'
|
|
17
18
|
import { generateScheme } from './wechat-scheme.ts'
|
|
18
19
|
|
|
@@ -33,11 +34,54 @@ export interface BridgeServerOptions {
|
|
|
33
34
|
}
|
|
34
35
|
|
|
35
36
|
const COOKIE = 'mbs'
|
|
37
|
+
const DEEPSEEK_LOGO = readFileSync(new URL('./deepseek-logo.svg', import.meta.url), 'utf8')
|
|
38
|
+
const DEEPSEEK_LOGO_DATA_URL = 'data:image/svg+xml;base64,' + Buffer.from(DEEPSEEK_LOGO).toString('base64')
|
|
36
39
|
|
|
37
|
-
const LANDING = `<!doctype html
|
|
38
|
-
<
|
|
39
|
-
<
|
|
40
|
-
|
|
40
|
+
const LANDING = `<!doctype html>
|
|
41
|
+
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="dark light"><title>DeepSeek Harness Mobile</title>
|
|
42
|
+
<style>
|
|
43
|
+
:root{color-scheme:dark;--page:#090d13;--field:#151b25;--field-focus:#1b2330;--label:#f4f7fb;--muted:#aeb8c8;--placeholder:#768296;--primary:#4d6bfe;--primary-hover:#5a76ff;--secondary:#222a37;--secondary-hover:#2a3443;--danger:#ff7b84}
|
|
44
|
+
:root[data-theme=light]{color-scheme:light;--page:#f6f8fc;--field:#e9edf5;--field-focus:#e2e8f3;--label:#182033;--muted:#5c687b;--placeholder:#7d8899;--primary:#405de6;--primary-hover:#3452dc;--secondary:#e1e7f1;--secondary-hover:#d8e0ed;--danger:#d93d54}
|
|
45
|
+
*{box-sizing:border-box}
|
|
46
|
+
html{-webkit-text-size-adjust:100%;text-size-adjust:100%;background:var(--page)}
|
|
47
|
+
body{min-height:100dvh;margin:0;padding:max(32px,env(safe-area-inset-top)) 16px max(28px,env(safe-area-inset-bottom));background:var(--page);color:var(--label);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
|
48
|
+
body::before{position:fixed;inset:0;content:"";pointer-events:none;background-image:linear-gradient(rgb(77 107 254/.045) 1px,transparent 1px),linear-gradient(90deg,rgb(77 107 254/.045) 1px,transparent 1px);background-size:32px 32px}
|
|
49
|
+
main{position:relative;width:min(100%,390px);margin:clamp(12px,5vh,48px) auto 0;padding:0 8px}
|
|
50
|
+
.brand{display:flex;align-items:center;justify-content:space-between;gap:16px}
|
|
51
|
+
.brand img{display:block;width:min(195px,65%);height:auto}
|
|
52
|
+
.product{color:var(--muted);font-size:11px;font-weight:700;text-transform:uppercase}
|
|
53
|
+
.preferences{display:flex;justify-content:flex-end;gap:8px;margin-top:22px}
|
|
54
|
+
.segmented{display:flex;padding:3px;border-radius:8px;background:var(--field)}
|
|
55
|
+
.preferences button{width:auto;height:30px;padding:0 10px;border-radius:6px;background:transparent;color:var(--muted);font-size:12px;font-weight:650}
|
|
56
|
+
.preferences button:hover{background:var(--field-focus)}
|
|
57
|
+
.preferences button[aria-pressed=true]{background:var(--primary);color:white}
|
|
58
|
+
.intro{margin:30px 0 28px}
|
|
59
|
+
h1{margin:0;font-size:22px;line-height:1.35;font-weight:650}
|
|
60
|
+
.scanFirst{margin:0;color:var(--muted);font-size:13px}
|
|
61
|
+
[hidden]{display:none!important}
|
|
62
|
+
#loginForm{padding-bottom:12px}
|
|
63
|
+
.field{display:grid;gap:7px}
|
|
64
|
+
.field+.field,.codeRow+.field{margin-top:16px}
|
|
65
|
+
label{color:var(--muted);font-size:12px;font-weight:600}
|
|
66
|
+
input,button{width:100%;min-width:0;height:46px;border:0;border-radius:8px;font:inherit}
|
|
67
|
+
input{padding:0 13px;outline:none;background:var(--field);color:var(--label);font-size:16px}
|
|
68
|
+
input::placeholder{color:var(--placeholder)}
|
|
69
|
+
input:focus{background:var(--field-focus);box-shadow:inset 0 -2px 0 var(--primary)}
|
|
70
|
+
#b{text-transform:uppercase;font-variant-numeric:tabular-nums}
|
|
71
|
+
.codeRow{display:grid;grid-template-columns:minmax(0,1fr) 92px;align-items:end;gap:8px;margin-top:16px}
|
|
72
|
+
button{background:var(--primary);color:white;font-weight:650;cursor:pointer;transition:background-color .16s ease,transform .08s ease}
|
|
73
|
+
button:hover{background:var(--primary-hover)}
|
|
74
|
+
button:active{transform:translateY(1px)}
|
|
75
|
+
button.ghost{background:var(--secondary);color:var(--label)}
|
|
76
|
+
button.ghost:hover{background:var(--secondary-hover)}
|
|
77
|
+
button:disabled{opacity:.6;cursor:wait}
|
|
78
|
+
#l{margin-top:22px}
|
|
79
|
+
p.err{min-height:20px;margin:12px 0 0;color:var(--danger);font-size:13px;line-height:20px}
|
|
80
|
+
@media(max-width:340px){main{padding:0 2px}.brand img{width:168px}.preferences{justify-content:flex-start}.preferences button{padding:0 8px}.codeRow{grid-template-columns:minmax(0,1fr) 82px}}
|
|
81
|
+
@media(prefers-reduced-motion:reduce){button{transition:none}}
|
|
82
|
+
</style></head><body>
|
|
83
|
+
<main aria-labelledby="title"><header class="brand"><img src="${DEEPSEEK_LOGO_DATA_URL}" alt="DeepSeek"><span class="product">Harness Mobile</span></header><nav class="preferences" aria-label="显示偏好"><div class="segmented"><button id="langZh" type="button" aria-pressed="true">中文</button><button id="langEn" type="button" aria-pressed="false">EN</button></div><div class="segmented"><button id="themeLight" type="button" aria-pressed="false" data-i18n="light">浅色</button><button id="themeDark" type="button" aria-pressed="true" data-i18n="dark">深色</button></div></nav><div class="intro"><h1 id="title" data-i18n="title">移动连接</h1></div><p class="scanFirst" id="scanFirst" data-i18n="scanFirst">请扫描桌面端二维码</p><section id="loginForm" hidden><div class="field"><label for="e" data-i18n="email">邮箱</label><input id="e" type="email" inputmode="email" autocomplete="email" placeholder="name@example.com" data-i18n-placeholder="emailPlaceholder"></div><div class="codeRow"><div class="field"><label for="c" data-i18n="code">验证码</label><input id="c" inputmode="numeric" autocomplete="one-time-code" placeholder="6 位验证码" data-i18n-placeholder="codePlaceholder"></div><button id="s" class="ghost" type="button" data-i18n="send">发送</button></div><div class="field"><label for="b" data-i18n="pairingCode">配对码</label><input id="b" autocomplete="off" placeholder="6 位字符" data-i18n-placeholder="pairingPlaceholder"></div><button id="l" type="button" data-i18n="connect">登录并连接</button><p class="err" id="x" role="alert"></p></section></main>
|
|
84
|
+
<script src="/bridge/client.js"></script></body></html>`
|
|
41
85
|
|
|
42
86
|
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
43
87
|
res.writeHead(status, { 'content-type': 'application/json' })
|
|
@@ -50,31 +94,155 @@ async function readBody(req: IncomingMessage): Promise<string> {
|
|
|
50
94
|
return Buffer.concat(chunks).toString('utf8')
|
|
51
95
|
}
|
|
52
96
|
|
|
97
|
+
function sameToken(expected: string, actual: string): boolean {
|
|
98
|
+
const left = Buffer.from(expected)
|
|
99
|
+
const right = Buffer.from(actual)
|
|
100
|
+
return left.length === right.length && timingSafeEqual(left, right)
|
|
101
|
+
}
|
|
102
|
+
|
|
53
103
|
function cookieToken(req: IncomingMessage): string {
|
|
54
104
|
const header = req.headers.cookie ?? ''
|
|
55
105
|
const match = header.match(new RegExp('(?:^|; )' + COOKIE + '=([^;]+)'))
|
|
56
106
|
return match ? decodeURIComponent(match[1]) : ''
|
|
57
107
|
}
|
|
58
108
|
|
|
59
|
-
/**
|
|
60
|
-
* Build the bridge server: `/bridge/*` owns auth/bind/landing plus the phone
|
|
61
|
-
* bootstrap assets; `/ws/bridge` and `/ws/client` are piped verbatim.
|
|
62
|
-
* @param store - user/token/binding store.
|
|
63
|
-
* @param options - mailer and external auth provider verifiers.
|
|
64
|
-
* @returns the node HTTP server (listen owned by the caller).
|
|
65
|
-
*/
|
|
66
109
|
/** Options for the bridge server. */
|
|
67
110
|
export interface BridgeServerRuntimeOptions extends BridgeServerOptions {
|
|
68
111
|
/** Pairing login ticket lifetime; defaults to five minutes. */
|
|
69
112
|
ticketTtlMs?: number
|
|
70
113
|
}
|
|
71
114
|
|
|
115
|
+
/** Device fields projected to the authenticated desktop, including live relay state. */
|
|
116
|
+
export interface BridgeDeviceView extends DeviceRecord {
|
|
117
|
+
online: boolean
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface PairingTicketRecord {
|
|
121
|
+
bridgeId: string
|
|
122
|
+
code: string
|
|
123
|
+
refreshToken: string
|
|
124
|
+
expiresAt: number
|
|
125
|
+
used: boolean
|
|
126
|
+
email2fa?: string
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function bearerToken(req: IncomingMessage): string {
|
|
130
|
+
return (req.headers.authorization ?? '').replace(/^Bearer /, '')
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function requestIp(req: IncomingMessage): string {
|
|
134
|
+
const forwarded = req.headers['x-forwarded-for']
|
|
135
|
+
const value = Array.isArray(forwarded) ? forwarded[0] : forwarded?.split(',')[0]
|
|
136
|
+
return value?.trim() || req.socket.remoteAddress || 'unknown'
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function requestDeviceName(req: IncomingMessage): string {
|
|
140
|
+
const userAgent = req.headers['user-agent'] ?? ''
|
|
141
|
+
const platform = /iPad/u.test(userAgent)
|
|
142
|
+
? 'iPad'
|
|
143
|
+
: /iPhone/u.test(userAgent)
|
|
144
|
+
? 'iPhone'
|
|
145
|
+
: /Android/u.test(userAgent)
|
|
146
|
+
? 'Android'
|
|
147
|
+
: /Windows/u.test(userAgent)
|
|
148
|
+
? 'Windows'
|
|
149
|
+
: /Macintosh/u.test(userAgent)
|
|
150
|
+
? 'Mac'
|
|
151
|
+
: 'Mobile browser'
|
|
152
|
+
const browser = /Edg\//u.test(userAgent)
|
|
153
|
+
? 'Edge'
|
|
154
|
+
: /Firefox\//u.test(userAgent)
|
|
155
|
+
? 'Firefox'
|
|
156
|
+
: /(?:Chrome|CriOS)\//u.test(userAgent)
|
|
157
|
+
? 'Chrome'
|
|
158
|
+
: /Safari\//u.test(userAgent)
|
|
159
|
+
? 'Safari'
|
|
160
|
+
: ''
|
|
161
|
+
return browser === '' ? platform : platform + ' · ' + browser
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Build the public bridge, pairing-ticket lifecycle, device registry, and
|
|
166
|
+
* ciphertext relay around stable desktop identities.
|
|
167
|
+
* @param store - durable identity, bridge, token, and device owner.
|
|
168
|
+
* @param options - mail and external authentication providers.
|
|
169
|
+
* @returns the Node HTTP server; its caller owns listen and close.
|
|
170
|
+
*/
|
|
72
171
|
export function createBridgeServer(store: UserStore, options: BridgeServerRuntimeOptions = {}) {
|
|
73
172
|
const externalAuth = options.externalAuth ?? {}
|
|
74
173
|
const mailer = options.mailer
|
|
75
174
|
const ticketTtlMs = options.ticketTtlMs ?? 5 * 60_000
|
|
76
175
|
const bridges = new Map<string, WebSocket>()
|
|
77
|
-
const tickets = new Map<string,
|
|
176
|
+
const tickets = new Map<string, PairingTicketRecord>()
|
|
177
|
+
const bridgeTickets = new Map<string, string>()
|
|
178
|
+
const clientsByDevice = new Map<string, Set<WebSocket>>()
|
|
179
|
+
|
|
180
|
+
// 持久设备记录是事实源,在线状态只由当前 WebSocket 集合投影。
|
|
181
|
+
const deviceViews = (bridgeId: string): BridgeDeviceView[] => store.devicesForBridge(bridgeId).map(device => ({
|
|
182
|
+
...device,
|
|
183
|
+
online: [...(clientsByDevice.get(device.id) ?? [])].some(socket => socket.readyState === WebSocket.OPEN),
|
|
184
|
+
}))
|
|
185
|
+
|
|
186
|
+
const notifyDevices = (bridgeId: string): void => {
|
|
187
|
+
const socket = bridges.get(bridgeId)
|
|
188
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'devices', devices: deviceViews(bridgeId) }))
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const issueTicket = (bridgeId: string, email2fa?: string): PairingTicketRecord => {
|
|
192
|
+
const previousCode = bridgeTickets.get(bridgeId)
|
|
193
|
+
if (previousCode !== undefined) tickets.delete(previousCode)
|
|
194
|
+
const createdAt = Date.now()
|
|
195
|
+
const ticket: PairingTicketRecord = {
|
|
196
|
+
bridgeId,
|
|
197
|
+
code: randomBytes(3).toString('hex'),
|
|
198
|
+
refreshToken: randomBytes(24).toString('hex'),
|
|
199
|
+
expiresAt: createdAt + ticketTtlMs,
|
|
200
|
+
used: false,
|
|
201
|
+
...email2fa ? { email2fa } : {},
|
|
202
|
+
}
|
|
203
|
+
tickets.set(ticket.code, ticket)
|
|
204
|
+
bridgeTickets.set(bridgeId, ticket.code)
|
|
205
|
+
return ticket
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const publicTicket = ({ code, refreshToken, expiresAt }: PairingTicketRecord) => ({ code, refreshToken, expiresAt })
|
|
209
|
+
|
|
210
|
+
const liveTicket = (code: string): PairingTicketRecord => {
|
|
211
|
+
const ticket = tickets.get(code)
|
|
212
|
+
const socket = ticket === undefined ? undefined : bridges.get(ticket.bridgeId)
|
|
213
|
+
if (ticket === undefined || socket?.readyState !== WebSocket.OPEN) throw new Error('unknown or offline pairing code')
|
|
214
|
+
if (ticket.used) throw new Error('pairing code already used')
|
|
215
|
+
if (ticket.expiresAt <= Date.now()) throw new Error('pairing code expired')
|
|
216
|
+
return ticket
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const pairDevice = (req: IncomingMessage, ticket: PairingTicketRecord, provider: string, externalId: string) => {
|
|
220
|
+
const priorToken = cookieToken(req)
|
|
221
|
+
const priorDevice = store.deviceFor(priorToken)
|
|
222
|
+
const token = store.loginExternal(provider, externalId)
|
|
223
|
+
const device = store.bindDevice(token, ticket.bridgeId, {
|
|
224
|
+
name: requestDeviceName(req),
|
|
225
|
+
ip: requestIp(req),
|
|
226
|
+
}, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
227
|
+
ticket.used = true
|
|
228
|
+
notifyDevices(ticket.bridgeId)
|
|
229
|
+
const socket = bridges.get(ticket.bridgeId)
|
|
230
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'paired', devices: deviceViews(ticket.bridgeId) }))
|
|
231
|
+
return { token, device }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const respondLogin = (res: ServerResponse, token: string): void => {
|
|
235
|
+
res.writeHead(200, {
|
|
236
|
+
'content-type': 'application/json',
|
|
237
|
+
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; SameSite=Lax; Path=/'],
|
|
238
|
+
})
|
|
239
|
+
res.end(JSON.stringify({ token }))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const fail = (res: ServerResponse, status: number, label: string, error: unknown): void => {
|
|
243
|
+
console.error('[dsh-mobile-bridge-server] ' + label, error)
|
|
244
|
+
json(res, status, { error: error instanceof Error ? error.message : String(error) })
|
|
245
|
+
}
|
|
78
246
|
|
|
79
247
|
const http = createServer((req, res) => {
|
|
80
248
|
void (async () => {
|
|
@@ -84,11 +252,21 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
84
252
|
res.end(LANDING)
|
|
85
253
|
return
|
|
86
254
|
}
|
|
255
|
+
if (url.pathname === '/bridge/deepseek-logo.svg') {
|
|
256
|
+
res.writeHead(200, { 'content-type': 'image/svg+xml; charset=utf-8', 'cache-control': 'public, max-age=86400' })
|
|
257
|
+
res.end(DEEPSEEK_LOGO)
|
|
258
|
+
return
|
|
259
|
+
}
|
|
87
260
|
if (url.pathname === '/bridge/client.js') {
|
|
88
261
|
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
89
262
|
res.end(CLIENT_SOURCE)
|
|
90
263
|
return
|
|
91
264
|
}
|
|
265
|
+
if (url.pathname === '/bridge/socket-client.js') {
|
|
266
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
267
|
+
res.end(SOCKET_CLIENT_SOURCE)
|
|
268
|
+
return
|
|
269
|
+
}
|
|
92
270
|
if (url.pathname === '/sw.js') {
|
|
93
271
|
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store', 'service-worker-allowed': '/' })
|
|
94
272
|
res.end(SW_SOURCE)
|
|
@@ -101,7 +279,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
101
279
|
const code = store.issueEmailCode(email)
|
|
102
280
|
await mailer(email, code)
|
|
103
281
|
json(res, 200, { sent: true })
|
|
104
|
-
} catch (error) {
|
|
282
|
+
} catch (error) { fail(res, 400, 'email code request failed', error) }
|
|
105
283
|
return
|
|
106
284
|
}
|
|
107
285
|
if (req.method === 'POST' && url.pathname === '/bridge/api/login/email') {
|
|
@@ -109,79 +287,88 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
109
287
|
const { email, code, bridge } = JSON.parse(await readBody(req)) as { email: string; code: string; bridge?: string }
|
|
110
288
|
store.consumeEmailCode(email, code)
|
|
111
289
|
const token = store.loginExternal('email', email.trim().toLowerCase())
|
|
112
|
-
if (typeof bridge === 'string' && bridge.trim()
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
290
|
+
if (typeof bridge === 'string' && bridge.trim() !== '') {
|
|
291
|
+
const ticket = liveTicket(bridge.trim())
|
|
292
|
+
const priorDevice = store.deviceFor(cookieToken(req))
|
|
293
|
+
store.bindDevice(token, ticket.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
294
|
+
ticket.used = true
|
|
295
|
+
const socket = bridges.get(ticket.bridgeId)
|
|
296
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'paired', devices: deviceViews(ticket.bridgeId) }))
|
|
297
|
+
} else {
|
|
298
|
+
const priorDevice = store.deviceFor(cookieToken(req))
|
|
299
|
+
if (priorDevice === undefined) throw new Error('scan a desktop pairing QR first')
|
|
300
|
+
store.bindDevice(token, priorDevice.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice.id)
|
|
301
|
+
}
|
|
302
|
+
respondLogin(res, token)
|
|
303
|
+
} catch (error) { fail(res, 401, 'email login failed', error) }
|
|
116
304
|
return
|
|
117
305
|
}
|
|
118
306
|
if (req.method === 'POST' && url.pathname === '/bridge/api/login/external') {
|
|
119
307
|
try {
|
|
120
308
|
const { provider, payload } = JSON.parse(await readBody(req)) as { provider: string; payload: Record<string, unknown> }
|
|
121
309
|
const verify = externalAuth[provider]
|
|
122
|
-
if (
|
|
123
|
-
const externalId = await verify(payload
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
res.end(JSON.stringify({ token }))
|
|
127
|
-
} catch (error) { json(res, 401, { error: error instanceof Error ? error.message : String(error) }) }
|
|
310
|
+
if (verify === undefined) throw new Error('unknown provider')
|
|
311
|
+
const externalId = await verify(payload)
|
|
312
|
+
respondLogin(res, store.loginExternal(provider, externalId))
|
|
313
|
+
} catch (error) { fail(res, 401, 'external login failed', error) }
|
|
128
314
|
return
|
|
129
315
|
}
|
|
130
316
|
if (req.method === 'POST' && url.pathname === '/bridge/api/login/bridge') {
|
|
131
|
-
// QR auto-login: possession of a live pairing code proves the desktop
|
|
132
|
-
// is online; the phone gets a session without typing credentials.
|
|
133
317
|
try {
|
|
134
318
|
const { code } = JSON.parse(await readBody(req)) as { code: string }
|
|
135
|
-
const ticket =
|
|
136
|
-
if (ticket
|
|
137
|
-
|
|
138
|
-
if (Date.now() - ticket.createdAt > ticketTtlMs) throw new Error('pairing code expired')
|
|
139
|
-
if (ticket.email2fa !== undefined && mailer !== undefined) {
|
|
140
|
-
// Optional second factor: the owner's inbox must confirm the scan.
|
|
319
|
+
const ticket = liveTicket(code)
|
|
320
|
+
if (ticket.email2fa !== undefined) {
|
|
321
|
+
if (mailer === undefined) throw new Error('email login not configured')
|
|
141
322
|
await mailer(ticket.email2fa, store.issueEmailCode(ticket.email2fa))
|
|
142
323
|
json(res, 200, { challenge: 'email' })
|
|
143
324
|
return
|
|
144
325
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': [`${COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/`] })
|
|
149
|
-
res.end(JSON.stringify({ token }))
|
|
150
|
-
} catch (error) { json(res, 401, { error: error instanceof Error ? error.message : String(error) }) }
|
|
326
|
+
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
327
|
+
respondLogin(res, token)
|
|
328
|
+
} catch (error) { fail(res, 401, 'pairing login failed', error) }
|
|
151
329
|
return
|
|
152
330
|
}
|
|
153
331
|
if (req.method === 'POST' && url.pathname === '/bridge/api/login/bridge/verify') {
|
|
154
332
|
try {
|
|
155
333
|
const { code, emailCode } = JSON.parse(await readBody(req)) as { code: string; emailCode: string }
|
|
156
|
-
const ticket =
|
|
157
|
-
if (ticket
|
|
158
|
-
if (ticket.used) throw new Error('pairing code already used')
|
|
159
|
-
if (Date.now() - ticket.createdAt > ticketTtlMs) throw new Error('pairing code expired')
|
|
334
|
+
const ticket = liveTicket(code)
|
|
335
|
+
if (ticket.email2fa === undefined) throw new Error('no pending challenge')
|
|
160
336
|
store.consumeEmailCode(ticket.email2fa, emailCode)
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': [`${COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/`] })
|
|
165
|
-
res.end(JSON.stringify({ token }))
|
|
166
|
-
} catch (error) { json(res, 401, { error: error instanceof Error ? error.message : String(error) }) }
|
|
337
|
+
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
338
|
+
respondLogin(res, token)
|
|
339
|
+
} catch (error) { fail(res, 401, 'pairing verification failed', error) }
|
|
167
340
|
return
|
|
168
341
|
}
|
|
169
|
-
const token = cookieToken(req) || (req
|
|
342
|
+
const token = cookieToken(req) || bearerToken(req)
|
|
170
343
|
if (req.method === 'GET' && url.pathname === '/bridge/api/me') {
|
|
171
344
|
const name = store.userFor(token)
|
|
172
|
-
if (
|
|
173
|
-
json(res, 200, { name, bridge: store.bridgeFor(token) })
|
|
345
|
+
if (name === undefined) { json(res, 401, { error: 'unknown token' }); return }
|
|
346
|
+
json(res, 200, { name, bridge: store.bridgeFor(token), device: store.deviceFor(token) })
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
if (req.method === 'GET' && url.pathname === '/bridge/api/bridge/devices') {
|
|
350
|
+
try {
|
|
351
|
+
const bridgeId = url.searchParams.get('bridgeId') ?? ''
|
|
352
|
+
store.verifyBridge(bridgeId, bearerToken(req))
|
|
353
|
+
json(res, 200, { devices: deviceViews(bridgeId) })
|
|
354
|
+
} catch (error) { fail(res, 401, 'device list failed', error) }
|
|
174
355
|
return
|
|
175
356
|
}
|
|
176
|
-
if (req.method === '
|
|
357
|
+
if (req.method === 'DELETE' && url.pathname.startsWith('/bridge/api/bridge/devices/')) {
|
|
177
358
|
try {
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
359
|
+
const bridgeId = url.searchParams.get('bridgeId') ?? ''
|
|
360
|
+
const deviceId = decodeURIComponent(url.pathname.slice('/bridge/api/bridge/devices/'.length))
|
|
361
|
+
store.verifyBridge(bridgeId, bearerToken(req))
|
|
362
|
+
const sockets = clientsByDevice.get(deviceId)
|
|
363
|
+
if (sockets !== undefined) for (const socket of sockets) socket.close(4003, 'device revoked')
|
|
364
|
+
clientsByDevice.delete(deviceId)
|
|
365
|
+
store.revokeDevice(bridgeId, deviceId)
|
|
366
|
+
notifyDevices(bridgeId)
|
|
367
|
+
json(res, 200, { devices: deviceViews(bridgeId) })
|
|
368
|
+
} catch (error) { fail(res, 400, 'device revoke failed', error) }
|
|
181
369
|
return
|
|
182
370
|
}
|
|
183
371
|
if (req.method === 'GET' && url.pathname === '/bridge/wxauth') {
|
|
184
|
-
// Mini-program web-view entry: wx.login code plus optional pairing.
|
|
185
372
|
const code = url.searchParams.get('code') ?? ''
|
|
186
373
|
const pair = url.searchParams.get('pair') ?? ''
|
|
187
374
|
const verify = externalAuth.wechat
|
|
@@ -189,59 +376,130 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
189
376
|
try {
|
|
190
377
|
const externalId = await verify({ code })
|
|
191
378
|
const token = store.loginExternal('wechat', externalId)
|
|
192
|
-
if (pair
|
|
379
|
+
if (pair !== '') {
|
|
380
|
+
const ticket = liveTicket(pair)
|
|
381
|
+
const priorDevice = store.deviceFor(cookieToken(req))
|
|
382
|
+
store.bindDevice(token, ticket.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
383
|
+
ticket.used = true
|
|
384
|
+
const socket = bridges.get(ticket.bridgeId)
|
|
385
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'paired', devices: deviceViews(ticket.bridgeId) }))
|
|
386
|
+
}
|
|
193
387
|
res.writeHead(302, {
|
|
194
|
-
'set-cookie': [
|
|
388
|
+
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; SameSite=Lax; Path=/'],
|
|
195
389
|
location: '/',
|
|
196
390
|
})
|
|
197
391
|
res.end()
|
|
198
|
-
} catch (error) {
|
|
392
|
+
} catch (error) { fail(res, 401, 'wechat login failed', error) }
|
|
199
393
|
return
|
|
200
394
|
}
|
|
201
395
|
if (req.method === 'POST' && url.pathname === '/bridge/api/scheme') {
|
|
202
396
|
if (options.wechatScheme === undefined) { json(res, 503, { error: 'wechat not configured' }); return }
|
|
203
397
|
try {
|
|
204
398
|
const { query } = JSON.parse(await readBody(req)) as { query: string }
|
|
205
|
-
const openlink = await generateScheme(options.wechatScheme,
|
|
399
|
+
const openlink = await generateScheme(options.wechatScheme, query.slice(0, 512))
|
|
206
400
|
json(res, 200, { openlink })
|
|
207
|
-
} catch (error) {
|
|
401
|
+
} catch (error) { fail(res, 502, 'wechat scheme failed', error) }
|
|
208
402
|
return
|
|
209
403
|
}
|
|
210
404
|
if (req.method === 'POST' && url.pathname === '/bridge/api/bridge/start') {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
405
|
+
try {
|
|
406
|
+
const { bridgeId, bridgeToken, email2fa } = JSON.parse(await readBody(req)) as { bridgeId: string; bridgeToken: string; email2fa?: string }
|
|
407
|
+
if (!/^[a-f0-9]{32}$/u.test(bridgeId) || !/^[a-f0-9]{64}$/u.test(bridgeToken)) throw new Error('invalid bridge credentials')
|
|
408
|
+
store.authenticateBridge(bridgeId, bridgeToken)
|
|
409
|
+
const ticket = issueTicket(bridgeId, typeof email2fa === 'string' && email2fa !== '' ? email2fa : undefined)
|
|
410
|
+
json(res, 200, publicTicket(ticket))
|
|
411
|
+
} catch (error) { fail(res, 401, 'bridge start failed', error) }
|
|
412
|
+
return
|
|
413
|
+
}
|
|
414
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/bridge/rotate') {
|
|
415
|
+
try {
|
|
416
|
+
const { bridgeId, code, refreshToken } = JSON.parse(await readBody(req)) as { bridgeId: string; code: string; refreshToken: string }
|
|
417
|
+
const ticket = tickets.get(code)
|
|
418
|
+
if (ticket === undefined || ticket.bridgeId !== bridgeId || !sameToken(ticket.refreshToken, refreshToken)) throw new Error('invalid pairing refresh token')
|
|
419
|
+
const socket = bridges.get(bridgeId)
|
|
420
|
+
if (socket?.readyState !== WebSocket.OPEN) throw new Error('bridge is offline')
|
|
421
|
+
json(res, 200, publicTicket(issueTicket(bridgeId, ticket.email2fa)))
|
|
422
|
+
} catch (error) { fail(res, 401, 'pairing rotation failed', error) }
|
|
216
423
|
return
|
|
217
424
|
}
|
|
218
425
|
json(res, 404, { error: 'not found' })
|
|
219
|
-
})()
|
|
426
|
+
})().catch(error => { fail(res, 500, 'request failed', error) })
|
|
220
427
|
})
|
|
221
428
|
|
|
222
429
|
const wss = new WebSocketServer({ noServer: true })
|
|
223
430
|
http.on('upgrade', (req, socket, head) => {
|
|
224
431
|
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
225
432
|
if (url.pathname === '/ws/bridge') {
|
|
226
|
-
const
|
|
227
|
-
|
|
433
|
+
const bridgeId = url.searchParams.get('bridgeId') ?? ''
|
|
434
|
+
const code = bridgeTickets.get(bridgeId)
|
|
435
|
+
const ticket = code === undefined ? undefined : tickets.get(code)
|
|
436
|
+
const credential = bearerToken(req)
|
|
437
|
+
if (ticket === undefined || !sameToken(ticket.refreshToken, credential)) { socket.destroy(); return }
|
|
228
438
|
wss.handleUpgrade(req, socket, head, ws => {
|
|
229
|
-
bridges.
|
|
230
|
-
|
|
439
|
+
const previous = bridges.get(bridgeId)
|
|
440
|
+
bridges.set(bridgeId, ws)
|
|
441
|
+
if (previous !== undefined && previous !== ws) previous.close(4001, 'desktop reconnected')
|
|
442
|
+
ws.on('message', raw => {
|
|
443
|
+
try {
|
|
444
|
+
const frame = JSON.parse(String(raw)) as Record<string, unknown>
|
|
445
|
+
if (typeof frame.id !== 'string') throw new Error('relay response is missing id')
|
|
446
|
+
// 服务端只解析外层设备前缀,E2EE blob 始终保持不透明。
|
|
447
|
+
const separator = frame.id.indexOf(':')
|
|
448
|
+
if (separator <= 0) throw new Error('relay response has an invalid route id')
|
|
449
|
+
const deviceId = frame.id.slice(0, separator)
|
|
450
|
+
const outgoing = JSON.stringify({ ...frame, id: frame.id.slice(separator + 1) })
|
|
451
|
+
for (const client of clientsByDevice.get(deviceId) ?? []) {
|
|
452
|
+
if (client.readyState === WebSocket.OPEN) client.send(outgoing)
|
|
453
|
+
}
|
|
454
|
+
} catch (error) {
|
|
455
|
+
console.error('[dsh-mobile-bridge-server] desktop relay frame failed', error)
|
|
456
|
+
}
|
|
457
|
+
})
|
|
458
|
+
ws.on('close', () => {
|
|
459
|
+
if (bridges.get(bridgeId) === ws) bridges.delete(bridgeId)
|
|
460
|
+
})
|
|
461
|
+
notifyDevices(bridgeId)
|
|
231
462
|
})
|
|
232
463
|
return
|
|
233
464
|
}
|
|
234
465
|
if (url.pathname === '/ws/client') {
|
|
235
466
|
const token = url.searchParams.get('token') ?? cookieToken(req)
|
|
236
|
-
const
|
|
237
|
-
const
|
|
238
|
-
if (
|
|
467
|
+
const device = store.deviceFor(token)
|
|
468
|
+
const bridgeId = device?.bridgeId
|
|
469
|
+
if (device === undefined || bridgeId === undefined) {
|
|
470
|
+
wss.handleUpgrade(req, socket, head, client => { client.close(4003, 'device revoked') })
|
|
471
|
+
return
|
|
472
|
+
}
|
|
473
|
+
if (bridges.get(bridgeId)?.readyState !== WebSocket.OPEN) {
|
|
474
|
+
wss.handleUpgrade(req, socket, head, client => { client.close(1012, 'desktop offline') })
|
|
475
|
+
return
|
|
476
|
+
}
|
|
239
477
|
wss.handleUpgrade(req, socket, head, client => {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
478
|
+
let connections = clientsByDevice.get(device.id)
|
|
479
|
+
if (connections === undefined) {
|
|
480
|
+
connections = new Set()
|
|
481
|
+
clientsByDevice.set(device.id, connections)
|
|
482
|
+
}
|
|
483
|
+
connections.add(client)
|
|
484
|
+
store.touchDevice(device.id, requestIp(req))
|
|
485
|
+
notifyDevices(bridgeId)
|
|
486
|
+
client.on('message', raw => {
|
|
487
|
+
try {
|
|
488
|
+
const frame = JSON.parse(String(raw)) as Record<string, unknown>
|
|
489
|
+
if (typeof frame.id !== 'string') throw new Error('relay request is missing id')
|
|
490
|
+
const desktop = bridges.get(bridgeId)
|
|
491
|
+
if (desktop?.readyState !== WebSocket.OPEN) { client.close(1012, 'desktop offline'); return }
|
|
492
|
+
desktop.send(JSON.stringify({ ...frame, id: device.id + ':' + frame.id }))
|
|
493
|
+
} catch (error) {
|
|
494
|
+
console.error('[dsh-mobile-bridge-server] phone relay frame failed', error)
|
|
495
|
+
client.close(1003, 'invalid relay frame')
|
|
496
|
+
}
|
|
497
|
+
})
|
|
498
|
+
client.on('close', () => {
|
|
499
|
+
connections.delete(client)
|
|
500
|
+
if (connections.size === 0) clientsByDevice.delete(device.id)
|
|
501
|
+
notifyDevices(bridgeId)
|
|
502
|
+
})
|
|
245
503
|
})
|
|
246
504
|
return
|
|
247
505
|
}
|