@sparkelf/dsh-mobile-bridge-server 0.2.1 → 0.2.3
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/LICENSE +21 -0
- package/QR_SCANNER_LICENSE +21 -0
- package/THIRD_PARTY_NOTICES.md +12 -0
- package/ZXING_CPP_LICENSE +201 -0
- package/ZXING_WASM_LICENSE +21 -0
- package/package.json +19 -2
- package/src/phone.ts +603 -19
- package/src/server.ts +153 -17
- package/src/wechat.spec.ts +0 -38
package/src/server.ts
CHANGED
|
@@ -10,8 +10,10 @@
|
|
|
10
10
|
|
|
11
11
|
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
12
12
|
import { readFileSync } from 'node:fs'
|
|
13
|
+
import { createRequire } from 'node:module'
|
|
14
|
+
import { dirname, resolve } from 'node:path'
|
|
13
15
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
14
|
-
import { WebSocket, WebSocketServer } from 'ws'
|
|
16
|
+
import { WebSocket, WebSocketServer, type RawData } from 'ws'
|
|
15
17
|
import { SW_SOURCE, CLIENT_SOURCE, SOCKET_CLIENT_SOURCE } from './phone.ts'
|
|
16
18
|
import { UserStore, type DeviceRecord } from './store.ts'
|
|
17
19
|
import type { WechatConfig } from './wechat.ts'
|
|
@@ -34,18 +36,24 @@ export interface BridgeServerOptions {
|
|
|
34
36
|
}
|
|
35
37
|
|
|
36
38
|
const COOKIE = 'mbs'
|
|
39
|
+
const require = createRequire(import.meta.url)
|
|
40
|
+
const QR_SCANNER_SOURCE = readFileSync(require.resolve('qr-scanner'), 'utf8')
|
|
41
|
+
const QR_SCANNER_WORKER_SOURCE = readFileSync(require.resolve('qr-scanner/qr-scanner-worker.min.js'), 'utf8')
|
|
42
|
+
const ZXING_READER_ENTRY = require.resolve('zxing-wasm/reader')
|
|
43
|
+
const ZXING_READER_SOURCE = readFileSync(resolve(dirname(ZXING_READER_ENTRY), '../../iife/reader/index.js'), 'utf8')
|
|
44
|
+
const ZXING_READER_WASM = readFileSync(require.resolve('zxing-wasm/reader/zxing_reader.wasm'))
|
|
37
45
|
const DEEPSEEK_LOGO = readFileSync(new URL('./deepseek-logo.svg', import.meta.url), 'utf8')
|
|
38
46
|
const DEEPSEEK_LOGO_DATA_URL = 'data:image/svg+xml;base64,' + Buffer.from(DEEPSEEK_LOGO).toString('base64')
|
|
39
47
|
|
|
40
48
|
const LANDING = `<!doctype html>
|
|
41
49
|
<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
50
|
<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}
|
|
51
|
+
: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;--grid:rgb(105 132 255/.12)}
|
|
52
|
+
: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;--grid:rgb(77 107 254/.045)}
|
|
45
53
|
*{box-sizing:border-box}
|
|
46
54
|
html{-webkit-text-size-adjust:100%;text-size-adjust:100%;background:var(--page)}
|
|
47
55
|
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(
|
|
56
|
+
body::before{position:fixed;inset:0;content:"";pointer-events:none;background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:32px 32px}
|
|
49
57
|
main{position:relative;width:min(100%,390px);margin:clamp(12px,5vh,48px) auto 0;padding:0 8px}
|
|
50
58
|
.brand{display:flex;align-items:center;justify-content:space-between;gap:16px}
|
|
51
59
|
.brand img{display:block;width:min(195px,65%);height:auto}
|
|
@@ -57,7 +65,26 @@ main{position:relative;width:min(100%,390px);margin:clamp(12px,5vh,48px) auto 0;
|
|
|
57
65
|
.preferences button[aria-pressed=true]{background:var(--primary);color:white}
|
|
58
66
|
.intro{margin:30px 0 28px}
|
|
59
67
|
h1{margin:0;font-size:22px;line-height:1.35;font-weight:650}
|
|
60
|
-
.scanFirst{margin:0;color:var(--muted);font-size:13px}
|
|
68
|
+
.scanFirst{display:grid;gap:14px;margin:0;color:var(--muted);font-size:13px}
|
|
69
|
+
.scanFirst p{margin:0}
|
|
70
|
+
.scanButton{max-width:220px}
|
|
71
|
+
.scanner{position:fixed;inset:0;z-index:20;display:grid;grid-template-rows:auto minmax(0,1fr) auto;background:#05070b;color:#f4f7fb;padding:max(12px,env(safe-area-inset-top)) 0 max(16px,env(safe-area-inset-bottom))}
|
|
72
|
+
.scannerHeader{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:0 16px 12px}
|
|
73
|
+
.scannerHeader h2{margin:0;font-size:18px;line-height:40px}
|
|
74
|
+
.scannerClose{width:40px;height:40px;padding:0;border-radius:50%;background:rgb(255 255 255/.1);font-size:26px;font-weight:400;line-height:40px}
|
|
75
|
+
.scannerClose:hover{background:rgb(255 255 255/.16)}
|
|
76
|
+
.scannerStage{position:relative;min-height:0;overflow:hidden;background:#000}
|
|
77
|
+
.scanner video{display:block;width:100%;height:100%;object-fit:cover}
|
|
78
|
+
.scannerFrame{border:2px solid #6f89ff;border-radius:8px;box-shadow:0 0 0 200vmax rgb(0 0 0/.34)}
|
|
79
|
+
.scannerFrame.manual{position:absolute;top:50%;left:50%;width:min(67vw,320px);aspect-ratio:1;transform:translate(-50%,-50%)}
|
|
80
|
+
.wasmOutline{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
|
|
81
|
+
.wasmOutline polygon{fill:rgb(69 196 129/.16);stroke:#45c481;stroke-width:4;vector-effect:non-scaling-stroke}
|
|
82
|
+
.scannerFrame.invalid .wasmOutline polygon{fill:rgb(255 104 120/.14);stroke:#ff6878}
|
|
83
|
+
.scannerFrame .code-outline-highlight{fill:rgb(69 196 129/.16)!important;stroke:#45c481!important;stroke-width:4!important;stroke-dasharray:none!important}
|
|
84
|
+
.scannerFrame.invalid .code-outline-highlight{fill:rgb(255 104 120/.14)!important;stroke:#ff6878!important}
|
|
85
|
+
.scannerStatus{min-height:48px;margin:0;padding:14px 20px 0;color:#c6cedb;text-align:center}
|
|
86
|
+
.scannerStatus.error{color:#ff9aa2}
|
|
87
|
+
body.scannerOpen{overflow:hidden}
|
|
61
88
|
[hidden]{display:none!important}
|
|
62
89
|
#loginForm{padding-bottom:12px}
|
|
63
90
|
.field{display:grid;gap:7px}
|
|
@@ -80,7 +107,7 @@ p.err{min-height:20px;margin:12px 0 0;color:var(--danger);font-size:13px;line-he
|
|
|
80
107
|
@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
108
|
@media(prefers-reduced-motion:reduce){button{transition:none}}
|
|
82
109
|
</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><
|
|
110
|
+
<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><section class="scanFirst" id="scanFirst"><p data-i18n="scanFirst">请扫描桌面端二维码</p><button id="openScanner" class="scanButton" type="button" data-i18n="openScanner">打开相机扫码</button></section><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><section id="scanner" class="scanner" role="dialog" aria-modal="true" aria-labelledby="scannerTitle" hidden><header class="scannerHeader"><h2 id="scannerTitle" data-i18n="scannerTitle">扫描配对二维码</h2><button id="closeScanner" class="scannerClose" type="button" aria-label="关闭相机" data-i18n-aria-label="closeScanner">×</button></header><div class="scannerStage"><video id="scannerVideo" autoplay muted playsinline></video><div id="scannerFrame" class="scannerFrame" aria-hidden="true"><svg id="wasmOutline" class="wasmOutline" aria-hidden="true"><polygon id="wasmOutlinePolygon"></polygon></svg></div></div><p id="scannerStatus" class="scannerStatus" role="status" data-i18n="cameraStarting">正在打开相机</p></section>
|
|
84
111
|
<script src="/bridge/client.js"></script></body></html>`
|
|
85
112
|
|
|
86
113
|
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
@@ -117,12 +144,23 @@ export interface BridgeDeviceView extends DeviceRecord {
|
|
|
117
144
|
online: boolean
|
|
118
145
|
}
|
|
119
146
|
|
|
147
|
+
const DEFAULT_SESSION_DAYS = 7
|
|
148
|
+
const MAX_SESSION_DAYS = 365
|
|
149
|
+
|
|
150
|
+
// 桌面桥接请求是保活期限的唯一输入边界;配对票据只保存已验证的整天数。
|
|
151
|
+
function sessionDays(value: unknown): number {
|
|
152
|
+
if (value === undefined) return DEFAULT_SESSION_DAYS
|
|
153
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > MAX_SESSION_DAYS) throw new Error('session days must be an integer from 1 to 365')
|
|
154
|
+
return value
|
|
155
|
+
}
|
|
156
|
+
|
|
120
157
|
interface PairingTicketRecord {
|
|
121
158
|
bridgeId: string
|
|
122
159
|
code: string
|
|
123
160
|
refreshToken: string
|
|
124
161
|
expiresAt: number
|
|
125
162
|
used: boolean
|
|
163
|
+
sessionDays: number
|
|
126
164
|
email2fa?: string
|
|
127
165
|
}
|
|
128
166
|
|
|
@@ -161,6 +199,50 @@ function requestDeviceName(req: IncomingMessage): string {
|
|
|
161
199
|
return browser === '' ? platform : platform + ' · ' + browser
|
|
162
200
|
}
|
|
163
201
|
|
|
202
|
+
const SCANNER_DIAGNOSTIC_EVENTS = new Set(['open', 'library', 'controls', 'camera', 'scan', 'adjustment', 'decoded', 'accepted', 'rejected', 'error', 'close'])
|
|
203
|
+
const SCANNER_STRING_FIELDS = new Map([['state', 80], ['name', 80], ['message', 320], ['facingMode', 80], ['focusMode', 80], ['exposureMode', 80]])
|
|
204
|
+
const SCANNER_NUMBER_FIELDS = new Set(['attempts', 'elapsedMs', 'width', 'height', 'frameRate', 'corners', 'zoom', 'focusDistance', 'zoomMin', 'zoomMax', 'focusMin', 'focusMax', 'sharpness'])
|
|
205
|
+
const SCANNER_SIGNED_NUMBER_FIELDS = new Set(['exposureMin', 'exposureMax', 'exposureCompensation'])
|
|
206
|
+
|
|
207
|
+
function rawDataByteLength(raw: RawData): number {
|
|
208
|
+
return Array.isArray(raw) ? raw.reduce((total, part) => total + part.byteLength, 0) : raw.byteLength
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Scanner diagnostics are an unauthenticated public ingress; only bounded, non-secret telemetry fields reach the server log.
|
|
212
|
+
function scannerDiagnostic(value: unknown): Record<string, string | number | boolean> {
|
|
213
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('scanner diagnostic must be an object')
|
|
214
|
+
const input = value as Record<string, unknown>
|
|
215
|
+
if (typeof input.event !== 'string' || !SCANNER_DIAGNOSTIC_EVENTS.has(input.event)) throw new Error('scanner diagnostic event is invalid')
|
|
216
|
+
const output: Record<string, string | number | boolean> = { event: input.event }
|
|
217
|
+
for (const [field, maxLength] of SCANNER_STRING_FIELDS) {
|
|
218
|
+
const fieldValue = input[field]
|
|
219
|
+
if (fieldValue === undefined) continue
|
|
220
|
+
if (typeof fieldValue !== 'string') throw new Error('scanner diagnostic ' + field + ' must be a string')
|
|
221
|
+
output[field] = fieldValue.slice(0, maxLength)
|
|
222
|
+
}
|
|
223
|
+
if (input.stack !== undefined) {
|
|
224
|
+
if (typeof input.stack !== 'string') throw new Error('scanner diagnostic stack must be a string')
|
|
225
|
+
output.stack = input.stack
|
|
226
|
+
}
|
|
227
|
+
for (const field of SCANNER_NUMBER_FIELDS) {
|
|
228
|
+
const fieldValue = input[field]
|
|
229
|
+
if (fieldValue === undefined) continue
|
|
230
|
+
if (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue) || fieldValue < 0) throw new Error('scanner diagnostic ' + field + ' must be a non-negative number')
|
|
231
|
+
output[field] = fieldValue
|
|
232
|
+
}
|
|
233
|
+
for (const field of SCANNER_SIGNED_NUMBER_FIELDS) {
|
|
234
|
+
const fieldValue = input[field]
|
|
235
|
+
if (fieldValue === undefined) continue
|
|
236
|
+
if (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue)) throw new Error('scanner diagnostic ' + field + ' must be a finite number')
|
|
237
|
+
output[field] = fieldValue
|
|
238
|
+
}
|
|
239
|
+
if (input.valid !== undefined) {
|
|
240
|
+
if (typeof input.valid !== 'boolean') throw new Error('scanner diagnostic valid must be a boolean')
|
|
241
|
+
output.valid = input.valid
|
|
242
|
+
}
|
|
243
|
+
return output
|
|
244
|
+
}
|
|
245
|
+
|
|
164
246
|
/**
|
|
165
247
|
* Build the public bridge, pairing-ticket lifecycle, device registry, and
|
|
166
248
|
* ciphertext relay around stable desktop identities.
|
|
@@ -188,7 +270,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
188
270
|
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'devices', devices: deviceViews(bridgeId) }))
|
|
189
271
|
}
|
|
190
272
|
|
|
191
|
-
const issueTicket = (bridgeId: string, email2fa?: string): PairingTicketRecord => {
|
|
273
|
+
const issueTicket = (bridgeId: string, cookieDays: number, email2fa?: string): PairingTicketRecord => {
|
|
192
274
|
const previousCode = bridgeTickets.get(bridgeId)
|
|
193
275
|
if (previousCode !== undefined) tickets.delete(previousCode)
|
|
194
276
|
const createdAt = Date.now()
|
|
@@ -198,6 +280,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
198
280
|
refreshToken: randomBytes(24).toString('hex'),
|
|
199
281
|
expiresAt: createdAt + ticketTtlMs,
|
|
200
282
|
used: false,
|
|
283
|
+
sessionDays: cookieDays,
|
|
201
284
|
...email2fa ? { email2fa } : {},
|
|
202
285
|
}
|
|
203
286
|
tickets.set(ticket.code, ticket)
|
|
@@ -231,10 +314,10 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
231
314
|
return { token, device }
|
|
232
315
|
}
|
|
233
316
|
|
|
234
|
-
const respondLogin = (res: ServerResponse, token: string): void => {
|
|
317
|
+
const respondLogin = (res: ServerResponse, token: string, days: number): void => {
|
|
235
318
|
res.writeHead(200, {
|
|
236
319
|
'content-type': 'application/json',
|
|
237
|
-
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; SameSite=Lax; Path
|
|
320
|
+
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=' + String(days * 86400)],
|
|
238
321
|
})
|
|
239
322
|
res.end(JSON.stringify({ token }))
|
|
240
323
|
}
|
|
@@ -257,6 +340,26 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
257
340
|
res.end(DEEPSEEK_LOGO)
|
|
258
341
|
return
|
|
259
342
|
}
|
|
343
|
+
if (url.pathname === '/bridge/qr-scanner.js') {
|
|
344
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
345
|
+
res.end(QR_SCANNER_SOURCE)
|
|
346
|
+
return
|
|
347
|
+
}
|
|
348
|
+
if (url.pathname === '/bridge/qr-scanner-worker.min.js') {
|
|
349
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
350
|
+
res.end(QR_SCANNER_WORKER_SOURCE)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
if (url.pathname === '/bridge/zxing-reader.js') {
|
|
354
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
355
|
+
res.end(ZXING_READER_SOURCE)
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
if (url.pathname === '/bridge/zxing-reader.wasm') {
|
|
359
|
+
res.writeHead(200, { 'content-type': 'application/wasm', 'cache-control': 'no-store' })
|
|
360
|
+
res.end(ZXING_READER_WASM)
|
|
361
|
+
return
|
|
362
|
+
}
|
|
260
363
|
if (url.pathname === '/bridge/client.js') {
|
|
261
364
|
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
262
365
|
res.end(CLIENT_SOURCE)
|
|
@@ -285,10 +388,12 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
285
388
|
if (req.method === 'POST' && url.pathname === '/bridge/api/login/email') {
|
|
286
389
|
try {
|
|
287
390
|
const { email, code, bridge } = JSON.parse(await readBody(req)) as { email: string; code: string; bridge?: string }
|
|
391
|
+
let days = DEFAULT_SESSION_DAYS
|
|
288
392
|
store.consumeEmailCode(email, code)
|
|
289
393
|
const token = store.loginExternal('email', email.trim().toLowerCase())
|
|
290
394
|
if (typeof bridge === 'string' && bridge.trim() !== '') {
|
|
291
395
|
const ticket = liveTicket(bridge.trim())
|
|
396
|
+
days = ticket.sessionDays
|
|
292
397
|
const priorDevice = store.deviceFor(cookieToken(req))
|
|
293
398
|
store.bindDevice(token, ticket.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
294
399
|
ticket.used = true
|
|
@@ -299,7 +404,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
299
404
|
if (priorDevice === undefined) throw new Error('scan a desktop pairing QR first')
|
|
300
405
|
store.bindDevice(token, priorDevice.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice.id)
|
|
301
406
|
}
|
|
302
|
-
respondLogin(res, token)
|
|
407
|
+
respondLogin(res, token, days)
|
|
303
408
|
} catch (error) { fail(res, 401, 'email login failed', error) }
|
|
304
409
|
return
|
|
305
410
|
}
|
|
@@ -309,7 +414,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
309
414
|
const verify = externalAuth[provider]
|
|
310
415
|
if (verify === undefined) throw new Error('unknown provider')
|
|
311
416
|
const externalId = await verify(payload)
|
|
312
|
-
respondLogin(res, store.loginExternal(provider, externalId))
|
|
417
|
+
respondLogin(res, store.loginExternal(provider, externalId), DEFAULT_SESSION_DAYS)
|
|
313
418
|
} catch (error) { fail(res, 401, 'external login failed', error) }
|
|
314
419
|
return
|
|
315
420
|
}
|
|
@@ -324,7 +429,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
324
429
|
return
|
|
325
430
|
}
|
|
326
431
|
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
327
|
-
respondLogin(res, token)
|
|
432
|
+
respondLogin(res, token, ticket.sessionDays)
|
|
328
433
|
} catch (error) { fail(res, 401, 'pairing login failed', error) }
|
|
329
434
|
return
|
|
330
435
|
}
|
|
@@ -335,7 +440,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
335
440
|
if (ticket.email2fa === undefined) throw new Error('no pending challenge')
|
|
336
441
|
store.consumeEmailCode(ticket.email2fa, emailCode)
|
|
337
442
|
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
338
|
-
respondLogin(res, token)
|
|
443
|
+
respondLogin(res, token, ticket.sessionDays)
|
|
339
444
|
} catch (error) { fail(res, 401, 'pairing verification failed', error) }
|
|
340
445
|
return
|
|
341
446
|
}
|
|
@@ -376,8 +481,10 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
376
481
|
try {
|
|
377
482
|
const externalId = await verify({ code })
|
|
378
483
|
const token = store.loginExternal('wechat', externalId)
|
|
484
|
+
let days = DEFAULT_SESSION_DAYS
|
|
379
485
|
if (pair !== '') {
|
|
380
486
|
const ticket = liveTicket(pair)
|
|
487
|
+
days = ticket.sessionDays
|
|
381
488
|
const priorDevice = store.deviceFor(cookieToken(req))
|
|
382
489
|
store.bindDevice(token, ticket.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
383
490
|
ticket.used = true
|
|
@@ -385,7 +492,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
385
492
|
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'paired', devices: deviceViews(ticket.bridgeId) }))
|
|
386
493
|
}
|
|
387
494
|
res.writeHead(302, {
|
|
388
|
-
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; SameSite=Lax; Path
|
|
495
|
+
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=' + String(days * 86400)],
|
|
389
496
|
location: '/',
|
|
390
497
|
})
|
|
391
498
|
res.end()
|
|
@@ -403,10 +510,11 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
403
510
|
}
|
|
404
511
|
if (req.method === 'POST' && url.pathname === '/bridge/api/bridge/start') {
|
|
405
512
|
try {
|
|
406
|
-
const { bridgeId, bridgeToken, email2fa } = JSON.parse(await readBody(req)) as { bridgeId: string; bridgeToken: string; email2fa?: string }
|
|
513
|
+
const { bridgeId, bridgeToken, email2fa, sessionDays: requestedDays } = JSON.parse(await readBody(req)) as { bridgeId: string; bridgeToken: string; email2fa?: string; sessionDays?: number }
|
|
407
514
|
if (!/^[a-f0-9]{32}$/u.test(bridgeId) || !/^[a-f0-9]{64}$/u.test(bridgeToken)) throw new Error('invalid bridge credentials')
|
|
515
|
+
const days = sessionDays(requestedDays)
|
|
408
516
|
store.authenticateBridge(bridgeId, bridgeToken)
|
|
409
|
-
const ticket = issueTicket(bridgeId, typeof email2fa === 'string' && email2fa !== '' ? email2fa : undefined)
|
|
517
|
+
const ticket = issueTicket(bridgeId, days, typeof email2fa === 'string' && email2fa !== '' ? email2fa : undefined)
|
|
410
518
|
json(res, 200, publicTicket(ticket))
|
|
411
519
|
} catch (error) { fail(res, 401, 'bridge start failed', error) }
|
|
412
520
|
return
|
|
@@ -418,7 +526,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
418
526
|
if (ticket === undefined || ticket.bridgeId !== bridgeId || !sameToken(ticket.refreshToken, refreshToken)) throw new Error('invalid pairing refresh token')
|
|
419
527
|
const socket = bridges.get(bridgeId)
|
|
420
528
|
if (socket?.readyState !== WebSocket.OPEN) throw new Error('bridge is offline')
|
|
421
|
-
json(res, 200, publicTicket(issueTicket(bridgeId, ticket.email2fa)))
|
|
529
|
+
json(res, 200, publicTicket(issueTicket(bridgeId, ticket.sessionDays, ticket.email2fa)))
|
|
422
530
|
} catch (error) { fail(res, 401, 'pairing rotation failed', error) }
|
|
423
531
|
return
|
|
424
532
|
}
|
|
@@ -429,6 +537,34 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
429
537
|
const wss = new WebSocketServer({ noServer: true })
|
|
430
538
|
http.on('upgrade', (req, socket, head) => {
|
|
431
539
|
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
540
|
+
if (url.pathname === '/ws/scanner') {
|
|
541
|
+
const origin = req.headers.origin
|
|
542
|
+
const host = req.headers.host ?? ''
|
|
543
|
+
if (typeof origin !== 'string' || (origin !== 'https://' + host && origin !== 'http://' + host)) { socket.destroy(); return }
|
|
544
|
+
wss.handleUpgrade(req, socket, head, scanner => {
|
|
545
|
+
const id = randomBytes(4).toString('hex')
|
|
546
|
+
let messages = 0
|
|
547
|
+
const lifetime = setTimeout(() => { scanner.close(1000, 'scanner timeout') }, 10 * 60_000)
|
|
548
|
+
console.info('[mobile-bridge scanner]', { id, event: 'connected', ip: requestIp(req), device: requestDeviceName(req) })
|
|
549
|
+
scanner.on('message', (raw, isBinary) => {
|
|
550
|
+
try {
|
|
551
|
+
if (isBinary) { scanner.close(1003, 'binary scanner diagnostic unsupported'); return }
|
|
552
|
+
if (rawDataByteLength(raw) > 8192) { scanner.close(1009, 'scanner diagnostic too large'); return }
|
|
553
|
+
messages += 1
|
|
554
|
+
if (messages > 180) { scanner.close(1008, 'scanner diagnostic limit reached'); return }
|
|
555
|
+
console.info('[mobile-bridge scanner]', { id, ...scannerDiagnostic(JSON.parse(String(raw))) })
|
|
556
|
+
} catch (error) {
|
|
557
|
+
console.warn('[mobile-bridge scanner]', { id, event: 'invalid', error })
|
|
558
|
+
scanner.close(1003, 'invalid scanner diagnostic')
|
|
559
|
+
}
|
|
560
|
+
})
|
|
561
|
+
scanner.on('close', (code, reason) => {
|
|
562
|
+
clearTimeout(lifetime)
|
|
563
|
+
console.info('[mobile-bridge scanner]', { id, event: 'disconnected', code, reason: String(reason).slice(0, 123), messages })
|
|
564
|
+
})
|
|
565
|
+
})
|
|
566
|
+
return
|
|
567
|
+
}
|
|
432
568
|
if (url.pathname === '/ws/bridge') {
|
|
433
569
|
const bridgeId = url.searchParams.get('bridgeId') ?? ''
|
|
434
570
|
const code = bridgeTickets.get(bridgeId)
|
package/src/wechat.spec.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
import { wechatConfigFromEnv, wechatMiniprogramVerifier, wechatVerifier } from './wechat.ts'
|
|
3
|
-
import { generateScheme } from './wechat-scheme.ts'
|
|
4
|
-
|
|
5
|
-
function stubFetch(body: unknown): typeof fetch {
|
|
6
|
-
return (async () => new Response(JSON.stringify(body), { status: 200 })) as typeof fetch
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
describe('wechat verifiers', () => {
|
|
10
|
-
it('open-platform verifier returns unionid when present, openid otherwise', async () => {
|
|
11
|
-
const withUnion = wechatVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ access_token: 't', openid: 'od-1', unionid: 'uu-1' }))
|
|
12
|
-
await expect(withUnion({ code: 'c1' })).resolves.toBe('uu-1')
|
|
13
|
-
const openOnly = wechatVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ access_token: 't', openid: 'od-2' }))
|
|
14
|
-
await expect(openOnly({ code: 'c2' })).resolves.toBe('od-2')
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
it('miniprogram verifier uses jscode2session and surfaces provider errors', async () => {
|
|
18
|
-
const verify = wechatMiniprogramVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ openid: 'mp-1' }))
|
|
19
|
-
await expect(verify({ code: 'wx-code' })).resolves.toBe('mp-1')
|
|
20
|
-
const failing = wechatMiniprogramVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ errcode: 40029, errmsg: 'invalid code' }))
|
|
21
|
-
await expect(failing({ code: 'bad' })).rejects.toThrow(/invalid code/)
|
|
22
|
-
await expect(verify({})).rejects.toThrow(/missing/)
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
it('generates a URL Scheme from the openlink', async () => {
|
|
26
|
-
const fetchImpl = (async (url: string | URL | Request) => {
|
|
27
|
-
const target = String(url)
|
|
28
|
-
if (target.includes('/cgi-bin/token')) return new Response(JSON.stringify({ access_token: 'tok-1', expires_in: 7200 }), { status: 200 })
|
|
29
|
-
return new Response(JSON.stringify({ errcode: 0, openlink: 'weixin://dl/business/?t=abc' }), { status: 200 })
|
|
30
|
-
}) as typeof fetch
|
|
31
|
-
await expect(generateScheme({ appId: 'a', appSecret: 's' }, 'pair=xyz', fetchImpl)).resolves.toBe('weixin://dl/business/?t=abc')
|
|
32
|
-
})
|
|
33
|
-
|
|
34
|
-
it('enables only when env carries both credentials', () => {
|
|
35
|
-
expect(wechatConfigFromEnv({})).toBeUndefined()
|
|
36
|
-
expect(wechatConfigFromEnv({ WECHAT_APP_ID: 'a', WECHAT_APP_SECRET: 'b' })).toEqual({ appId: 'a', appSecret: 'b' })
|
|
37
|
-
})
|
|
38
|
-
})
|