@sparkelf/dsh-mobile-bridge-server 0.2.0 → 0.2.2
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 +2 -1
- package/src/phone.ts +96 -5
- package/src/server.ts +55 -17
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.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Multi-user bridge server connecting mobile browsers to local DeepSeek Harness instances through outbound tunnels.",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"dsh-mobile-bridge-server": "src/index.ts"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
+
"jsqr": "^1.4.0",
|
|
12
13
|
"nodemailer": "^6.9.0",
|
|
13
14
|
"ws": "^8.18.0"
|
|
14
15
|
}
|
package/src/phone.ts
CHANGED
|
@@ -138,7 +138,7 @@ function wsReady() {
|
|
|
138
138
|
}
|
|
139
139
|
if ((full.headers?.['content-type'] ?? '').includes('text/html')) {
|
|
140
140
|
let html = new TextDecoder().decode(body)
|
|
141
|
-
if (!html.includes('/bridge/socket-client.js')) html = html.replace('</head>', '<script src="/bridge/socket-client.js"></script
|
|
141
|
+
if (!html.includes('/bridge/socket-client.js')) html = html.replace('</head>', '<script src="/bridge/socket-client.js"></script></head>')
|
|
142
142
|
body = new TextEncoder().encode(html)
|
|
143
143
|
}
|
|
144
144
|
pending.delete(frame.id)
|
|
@@ -329,7 +329,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
329
329
|
var $ = function (id) { return document.getElementById(id) }
|
|
330
330
|
var COPY = {
|
|
331
331
|
zh: {
|
|
332
|
-
preferences: '显示偏好', title: '移动连接', scanFirst: '
|
|
332
|
+
preferences: '显示偏好', title: '移动连接', scanFirst: '扫描桌面端显示的配对二维码', openScanner: '打开相机扫码', scannerTitle: '扫描配对二维码', closeScanner: '关闭相机', cameraStarting: '正在打开相机', cameraReady: '将二维码放入扫描框', cameraUnavailable: '无法使用相机,请检查浏览器相机权限。', invalidPairQr: '请扫描桌面端显示的 Mobile Bridge 配对二维码。', email: '邮箱', emailPlaceholder: 'name@example.com',
|
|
333
333
|
code: '验证码', codePlaceholder: '6 位验证码', send: '发送', sending: '发送中', sent: '验证码已发送',
|
|
334
334
|
pairingCode: '配对码', pairingPlaceholder: '6 位字符', connect: '登录并连接', connecting: '正在连接', light: '浅色', dark: '深色',
|
|
335
335
|
ownerCode: '桌面所有者邮箱收到验证码,请输入', passphrase: '输入桌面端设置的加密口令', cancelled: '已取消',
|
|
@@ -338,7 +338,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
338
338
|
usedPair: '配对码已使用,请扫描最新二维码。', invalidCode: '验证码无效或已过期。'
|
|
339
339
|
},
|
|
340
340
|
en: {
|
|
341
|
-
preferences: 'Display preferences', title: 'Mobile connection', scanFirst: 'Scan the QR code shown on the desktop', email: 'Email', emailPlaceholder: 'name@example.com',
|
|
341
|
+
preferences: 'Display preferences', title: 'Mobile connection', scanFirst: 'Scan the pairing QR shown on the desktop', openScanner: 'Open camera scanner', scannerTitle: 'Scan pairing QR', closeScanner: 'Close camera', cameraStarting: 'Opening camera', cameraReady: 'Place the QR code inside the frame', cameraUnavailable: 'The camera is unavailable. Check this browser’s camera permission.', invalidPairQr: 'Scan the Mobile Bridge pairing QR shown on the desktop.', email: 'Email', emailPlaceholder: 'name@example.com',
|
|
342
342
|
code: 'Verification code', codePlaceholder: '6-digit code', send: 'Send', sending: 'Sending', sent: 'Code sent',
|
|
343
343
|
pairingCode: 'Pairing code', pairingPlaceholder: '6 characters', connect: 'Sign in and connect', connecting: 'Connecting', light: 'Light', dark: 'Dark',
|
|
344
344
|
ownerCode: 'Enter the code sent to the desktop owner email', passphrase: 'Enter the passphrase configured on the desktop', cancelled: 'Cancelled',
|
|
@@ -355,6 +355,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
355
355
|
document.querySelector('.preferences').setAttribute('aria-label', tr('preferences'))
|
|
356
356
|
document.querySelectorAll('[data-i18n]').forEach(function (node) { node.textContent = tr(node.getAttribute('data-i18n')) })
|
|
357
357
|
document.querySelectorAll('[data-i18n-placeholder]').forEach(function (node) { node.placeholder = tr(node.getAttribute('data-i18n-placeholder')) })
|
|
358
|
+
document.querySelectorAll('[data-i18n-aria-label]').forEach(function (node) { node.setAttribute('aria-label', tr(node.getAttribute('data-i18n-aria-label'))) })
|
|
358
359
|
$('langZh').setAttribute('aria-pressed', String(language === 'zh'))
|
|
359
360
|
$('langEn').setAttribute('aria-pressed', String(language === 'en'))
|
|
360
361
|
}
|
|
@@ -428,6 +429,92 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
428
429
|
location.assign('/')
|
|
429
430
|
}
|
|
430
431
|
|
|
432
|
+
var scannerStream = null
|
|
433
|
+
var scannerAnimation = 0
|
|
434
|
+
var lastScannedValue = ''
|
|
435
|
+
var lastScanAt = 0
|
|
436
|
+
var scannerCanvas = document.createElement('canvas')
|
|
437
|
+
var scannerContext = scannerCanvas.getContext('2d', { willReadFrequently: true })
|
|
438
|
+
|
|
439
|
+
// 相机轨道只属于取景页;关闭、识别成功和页面离开都会立即释放设备。
|
|
440
|
+
function stopScanner() {
|
|
441
|
+
cancelAnimationFrame(scannerAnimation)
|
|
442
|
+
scannerAnimation = 0
|
|
443
|
+
if (scannerStream) scannerStream.getTracks().forEach(function (track) { track.stop() })
|
|
444
|
+
scannerStream = null
|
|
445
|
+
$('scannerVideo').srcObject = null
|
|
446
|
+
$('scanner').hidden = true
|
|
447
|
+
document.body.classList.remove('scannerOpen')
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function setScannerStatus(key, error) {
|
|
451
|
+
$('scannerStatus').textContent = tr(key)
|
|
452
|
+
$('scannerStatus').classList.toggle('error', error)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// 摄像头二维码是外部输入;这里只接受当前 relay 的配对入口,再交给既有 hash 配对流程。
|
|
456
|
+
function acceptScannedPair(value) {
|
|
457
|
+
var target = new URL(value)
|
|
458
|
+
if (target.origin !== location.origin || target.pathname !== '/bridge/' || !target.hash) throw new Error('invalidPairQr')
|
|
459
|
+
stopScanner()
|
|
460
|
+
location.assign('/bridge/' + target.hash)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function scanCameraFrame(now) {
|
|
464
|
+
var video = $('scannerVideo')
|
|
465
|
+
if (video.readyState >= 2 && now - lastScanAt >= 120) {
|
|
466
|
+
lastScanAt = now
|
|
467
|
+
var sourceSize = Math.min(video.videoWidth, video.videoHeight)
|
|
468
|
+
var outputSize = Math.min(sourceSize, 640)
|
|
469
|
+
scannerCanvas.width = outputSize
|
|
470
|
+
scannerCanvas.height = outputSize
|
|
471
|
+
scannerContext.drawImage(video, (video.videoWidth - sourceSize) / 2, (video.videoHeight - sourceSize) / 2, sourceSize, sourceSize, 0, 0, outputSize, outputSize)
|
|
472
|
+
var pixels = scannerContext.getImageData(0, 0, outputSize, outputSize)
|
|
473
|
+
var decoded = window.jsQR(pixels.data, outputSize, outputSize, { inversionAttempts: 'dontInvert' })
|
|
474
|
+
if (decoded && decoded.data !== lastScannedValue) {
|
|
475
|
+
lastScannedValue = decoded.data
|
|
476
|
+
try {
|
|
477
|
+
acceptScannedPair(decoded.data)
|
|
478
|
+
return
|
|
479
|
+
} catch (error) {
|
|
480
|
+
console.info('[dsh-mobile-bridge] camera QR rejected', error)
|
|
481
|
+
setScannerStatus('invalidPairQr', true)
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
scannerAnimation = requestAnimationFrame(scanCameraFrame)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function openScanner() {
|
|
489
|
+
$('scanner').hidden = false
|
|
490
|
+
document.body.classList.add('scannerOpen')
|
|
491
|
+
lastScannedValue = ''
|
|
492
|
+
lastScanAt = 0
|
|
493
|
+
setScannerStatus('cameraStarting', false)
|
|
494
|
+
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
|
495
|
+
setScannerStatus('cameraUnavailable', true)
|
|
496
|
+
return
|
|
497
|
+
}
|
|
498
|
+
navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: { ideal: 'environment' } } })
|
|
499
|
+
.then(function (stream) {
|
|
500
|
+
scannerStream = stream
|
|
501
|
+
$('scannerVideo').srcObject = stream
|
|
502
|
+
return $('scannerVideo').play()
|
|
503
|
+
})
|
|
504
|
+
.then(function () {
|
|
505
|
+
setScannerStatus('cameraReady', false)
|
|
506
|
+
scannerAnimation = requestAnimationFrame(scanCameraFrame)
|
|
507
|
+
})
|
|
508
|
+
.catch(function (error) {
|
|
509
|
+
console.info('[dsh-mobile-bridge] camera start failed', error)
|
|
510
|
+
setScannerStatus('cameraUnavailable', true)
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
$('openScanner').onclick = openScanner
|
|
515
|
+
$('closeScanner').onclick = stopScanner
|
|
516
|
+
window.addEventListener('pagehide', stopScanner)
|
|
517
|
+
|
|
431
518
|
var fragment = location.hash.slice(1)
|
|
432
519
|
if (fragment) {
|
|
433
520
|
try {
|
|
@@ -465,8 +552,12 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
465
552
|
var stored = localStorage.getItem('dshmb-pair')
|
|
466
553
|
$('loginForm').hidden = !stored
|
|
467
554
|
$('scanFirst').hidden = !!stored
|
|
468
|
-
if (!fragment && stored
|
|
469
|
-
|
|
555
|
+
if (!fragment && stored) {
|
|
556
|
+
$('x').textContent = tr('connecting')
|
|
557
|
+
api('/api/me')
|
|
558
|
+
.then(function () { return registerSw(JSON.parse(stored)) })
|
|
559
|
+
.then(navigateToHarness)
|
|
560
|
+
.catch(showError)
|
|
470
561
|
}
|
|
471
562
|
$('s').onclick = function () {
|
|
472
563
|
var button = $('s')
|
package/src/server.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
12
12
|
import { readFileSync } from 'node:fs'
|
|
13
|
+
import { createRequire } from 'node:module'
|
|
13
14
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
14
15
|
import { WebSocket, WebSocketServer } from 'ws'
|
|
15
16
|
import { SW_SOURCE, CLIENT_SOURCE, SOCKET_CLIENT_SOURCE } from './phone.ts'
|
|
@@ -34,18 +35,20 @@ export interface BridgeServerOptions {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
const COOKIE = 'mbs'
|
|
38
|
+
const require = createRequire(import.meta.url)
|
|
39
|
+
const JSQR_SOURCE = readFileSync(require.resolve('jsqr'), 'utf8')
|
|
37
40
|
const DEEPSEEK_LOGO = readFileSync(new URL('./deepseek-logo.svg', import.meta.url), 'utf8')
|
|
38
41
|
const DEEPSEEK_LOGO_DATA_URL = 'data:image/svg+xml;base64,' + Buffer.from(DEEPSEEK_LOGO).toString('base64')
|
|
39
42
|
|
|
40
43
|
const LANDING = `<!doctype html>
|
|
41
44
|
<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
45
|
<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}
|
|
46
|
+
: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)}
|
|
47
|
+
: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
48
|
*{box-sizing:border-box}
|
|
46
49
|
html{-webkit-text-size-adjust:100%;text-size-adjust:100%;background:var(--page)}
|
|
47
50
|
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(
|
|
51
|
+
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
52
|
main{position:relative;width:min(100%,390px);margin:clamp(12px,5vh,48px) auto 0;padding:0 8px}
|
|
50
53
|
.brand{display:flex;align-items:center;justify-content:space-between;gap:16px}
|
|
51
54
|
.brand img{display:block;width:min(195px,65%);height:auto}
|
|
@@ -57,7 +60,20 @@ main{position:relative;width:min(100%,390px);margin:clamp(12px,5vh,48px) auto 0;
|
|
|
57
60
|
.preferences button[aria-pressed=true]{background:var(--primary);color:white}
|
|
58
61
|
.intro{margin:30px 0 28px}
|
|
59
62
|
h1{margin:0;font-size:22px;line-height:1.35;font-weight:650}
|
|
60
|
-
.scanFirst{margin:0;color:var(--muted);font-size:13px}
|
|
63
|
+
.scanFirst{display:grid;gap:14px;margin:0;color:var(--muted);font-size:13px}
|
|
64
|
+
.scanFirst p{margin:0}
|
|
65
|
+
.scanButton{max-width:220px}
|
|
66
|
+
.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))}
|
|
67
|
+
.scannerHeader{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:0 16px 12px}
|
|
68
|
+
.scannerHeader h2{margin:0;font-size:18px;line-height:40px}
|
|
69
|
+
.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}
|
|
70
|
+
.scannerClose:hover{background:rgb(255 255 255/.16)}
|
|
71
|
+
.scannerStage{position:relative;min-height:0;overflow:hidden;background:#000}
|
|
72
|
+
.scanner video{display:block;width:100%;height:100%;object-fit:cover}
|
|
73
|
+
.scannerFrame{position:absolute;top:50%;left:50%;width:min(72vw,320px);aspect-ratio:1;transform:translate(-50%,-50%);border:2px solid #6f89ff;border-radius:8px;box-shadow:0 0 0 200vmax rgb(0 0 0/.34)}
|
|
74
|
+
.scannerStatus{min-height:48px;margin:0;padding:14px 20px 0;color:#c6cedb;text-align:center}
|
|
75
|
+
.scannerStatus.error{color:#ff9aa2}
|
|
76
|
+
body.scannerOpen{overflow:hidden}
|
|
61
77
|
[hidden]{display:none!important}
|
|
62
78
|
#loginForm{padding-bottom:12px}
|
|
63
79
|
.field{display:grid;gap:7px}
|
|
@@ -80,8 +96,8 @@ p.err{min-height:20px;margin:12px 0 0;color:var(--danger);font-size:13px;line-he
|
|
|
80
96
|
@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
97
|
@media(prefers-reduced-motion:reduce){button{transition:none}}
|
|
82
98
|
</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><
|
|
84
|
-
<script src="/bridge/client.js"></script></body></html>`
|
|
99
|
+
<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 class="scannerFrame" aria-hidden="true"></div></div><p id="scannerStatus" class="scannerStatus" role="status" data-i18n="cameraStarting">正在打开相机</p></section>
|
|
100
|
+
<script src="/bridge/jsqr.js"></script><script src="/bridge/client.js"></script></body></html>`
|
|
85
101
|
|
|
86
102
|
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
87
103
|
res.writeHead(status, { 'content-type': 'application/json' })
|
|
@@ -117,12 +133,23 @@ export interface BridgeDeviceView extends DeviceRecord {
|
|
|
117
133
|
online: boolean
|
|
118
134
|
}
|
|
119
135
|
|
|
136
|
+
const DEFAULT_SESSION_DAYS = 7
|
|
137
|
+
const MAX_SESSION_DAYS = 365
|
|
138
|
+
|
|
139
|
+
// 桌面桥接请求是保活期限的唯一输入边界;配对票据只保存已验证的整天数。
|
|
140
|
+
function sessionDays(value: unknown): number {
|
|
141
|
+
if (value === undefined) return DEFAULT_SESSION_DAYS
|
|
142
|
+
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')
|
|
143
|
+
return value
|
|
144
|
+
}
|
|
145
|
+
|
|
120
146
|
interface PairingTicketRecord {
|
|
121
147
|
bridgeId: string
|
|
122
148
|
code: string
|
|
123
149
|
refreshToken: string
|
|
124
150
|
expiresAt: number
|
|
125
151
|
used: boolean
|
|
152
|
+
sessionDays: number
|
|
126
153
|
email2fa?: string
|
|
127
154
|
}
|
|
128
155
|
|
|
@@ -188,7 +215,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
188
215
|
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'devices', devices: deviceViews(bridgeId) }))
|
|
189
216
|
}
|
|
190
217
|
|
|
191
|
-
const issueTicket = (bridgeId: string, email2fa?: string): PairingTicketRecord => {
|
|
218
|
+
const issueTicket = (bridgeId: string, cookieDays: number, email2fa?: string): PairingTicketRecord => {
|
|
192
219
|
const previousCode = bridgeTickets.get(bridgeId)
|
|
193
220
|
if (previousCode !== undefined) tickets.delete(previousCode)
|
|
194
221
|
const createdAt = Date.now()
|
|
@@ -198,6 +225,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
198
225
|
refreshToken: randomBytes(24).toString('hex'),
|
|
199
226
|
expiresAt: createdAt + ticketTtlMs,
|
|
200
227
|
used: false,
|
|
228
|
+
sessionDays: cookieDays,
|
|
201
229
|
...email2fa ? { email2fa } : {},
|
|
202
230
|
}
|
|
203
231
|
tickets.set(ticket.code, ticket)
|
|
@@ -231,10 +259,10 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
231
259
|
return { token, device }
|
|
232
260
|
}
|
|
233
261
|
|
|
234
|
-
const respondLogin = (res: ServerResponse, token: string): void => {
|
|
262
|
+
const respondLogin = (res: ServerResponse, token: string, days: number): void => {
|
|
235
263
|
res.writeHead(200, {
|
|
236
264
|
'content-type': 'application/json',
|
|
237
|
-
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; SameSite=Lax; Path
|
|
265
|
+
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=' + String(days * 86400)],
|
|
238
266
|
})
|
|
239
267
|
res.end(JSON.stringify({ token }))
|
|
240
268
|
}
|
|
@@ -257,6 +285,11 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
257
285
|
res.end(DEEPSEEK_LOGO)
|
|
258
286
|
return
|
|
259
287
|
}
|
|
288
|
+
if (url.pathname === '/bridge/jsqr.js') {
|
|
289
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'public, max-age=86400' })
|
|
290
|
+
res.end(JSQR_SOURCE)
|
|
291
|
+
return
|
|
292
|
+
}
|
|
260
293
|
if (url.pathname === '/bridge/client.js') {
|
|
261
294
|
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
262
295
|
res.end(CLIENT_SOURCE)
|
|
@@ -285,10 +318,12 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
285
318
|
if (req.method === 'POST' && url.pathname === '/bridge/api/login/email') {
|
|
286
319
|
try {
|
|
287
320
|
const { email, code, bridge } = JSON.parse(await readBody(req)) as { email: string; code: string; bridge?: string }
|
|
321
|
+
let days = DEFAULT_SESSION_DAYS
|
|
288
322
|
store.consumeEmailCode(email, code)
|
|
289
323
|
const token = store.loginExternal('email', email.trim().toLowerCase())
|
|
290
324
|
if (typeof bridge === 'string' && bridge.trim() !== '') {
|
|
291
325
|
const ticket = liveTicket(bridge.trim())
|
|
326
|
+
days = ticket.sessionDays
|
|
292
327
|
const priorDevice = store.deviceFor(cookieToken(req))
|
|
293
328
|
store.bindDevice(token, ticket.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
294
329
|
ticket.used = true
|
|
@@ -299,7 +334,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
299
334
|
if (priorDevice === undefined) throw new Error('scan a desktop pairing QR first')
|
|
300
335
|
store.bindDevice(token, priorDevice.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice.id)
|
|
301
336
|
}
|
|
302
|
-
respondLogin(res, token)
|
|
337
|
+
respondLogin(res, token, days)
|
|
303
338
|
} catch (error) { fail(res, 401, 'email login failed', error) }
|
|
304
339
|
return
|
|
305
340
|
}
|
|
@@ -309,7 +344,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
309
344
|
const verify = externalAuth[provider]
|
|
310
345
|
if (verify === undefined) throw new Error('unknown provider')
|
|
311
346
|
const externalId = await verify(payload)
|
|
312
|
-
respondLogin(res, store.loginExternal(provider, externalId))
|
|
347
|
+
respondLogin(res, store.loginExternal(provider, externalId), DEFAULT_SESSION_DAYS)
|
|
313
348
|
} catch (error) { fail(res, 401, 'external login failed', error) }
|
|
314
349
|
return
|
|
315
350
|
}
|
|
@@ -324,7 +359,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
324
359
|
return
|
|
325
360
|
}
|
|
326
361
|
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
327
|
-
respondLogin(res, token)
|
|
362
|
+
respondLogin(res, token, ticket.sessionDays)
|
|
328
363
|
} catch (error) { fail(res, 401, 'pairing login failed', error) }
|
|
329
364
|
return
|
|
330
365
|
}
|
|
@@ -335,7 +370,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
335
370
|
if (ticket.email2fa === undefined) throw new Error('no pending challenge')
|
|
336
371
|
store.consumeEmailCode(ticket.email2fa, emailCode)
|
|
337
372
|
const { token } = pairDevice(req, ticket, 'bridge', randomBytes(12).toString('hex'))
|
|
338
|
-
respondLogin(res, token)
|
|
373
|
+
respondLogin(res, token, ticket.sessionDays)
|
|
339
374
|
} catch (error) { fail(res, 401, 'pairing verification failed', error) }
|
|
340
375
|
return
|
|
341
376
|
}
|
|
@@ -376,8 +411,10 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
376
411
|
try {
|
|
377
412
|
const externalId = await verify({ code })
|
|
378
413
|
const token = store.loginExternal('wechat', externalId)
|
|
414
|
+
let days = DEFAULT_SESSION_DAYS
|
|
379
415
|
if (pair !== '') {
|
|
380
416
|
const ticket = liveTicket(pair)
|
|
417
|
+
days = ticket.sessionDays
|
|
381
418
|
const priorDevice = store.deviceFor(cookieToken(req))
|
|
382
419
|
store.bindDevice(token, ticket.bridgeId, { name: requestDeviceName(req), ip: requestIp(req) }, priorDevice?.bridgeId === ticket.bridgeId ? priorDevice.id : undefined)
|
|
383
420
|
ticket.used = true
|
|
@@ -385,7 +422,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
385
422
|
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ control: 'paired', devices: deviceViews(ticket.bridgeId) }))
|
|
386
423
|
}
|
|
387
424
|
res.writeHead(302, {
|
|
388
|
-
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; SameSite=Lax; Path
|
|
425
|
+
'set-cookie': [COOKIE + '=' + encodeURIComponent(token) + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=' + String(days * 86400)],
|
|
389
426
|
location: '/',
|
|
390
427
|
})
|
|
391
428
|
res.end()
|
|
@@ -403,10 +440,11 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
403
440
|
}
|
|
404
441
|
if (req.method === 'POST' && url.pathname === '/bridge/api/bridge/start') {
|
|
405
442
|
try {
|
|
406
|
-
const { bridgeId, bridgeToken, email2fa } = JSON.parse(await readBody(req)) as { bridgeId: string; bridgeToken: string; email2fa?: string }
|
|
443
|
+
const { bridgeId, bridgeToken, email2fa, sessionDays: requestedDays } = JSON.parse(await readBody(req)) as { bridgeId: string; bridgeToken: string; email2fa?: string; sessionDays?: number }
|
|
407
444
|
if (!/^[a-f0-9]{32}$/u.test(bridgeId) || !/^[a-f0-9]{64}$/u.test(bridgeToken)) throw new Error('invalid bridge credentials')
|
|
445
|
+
const days = sessionDays(requestedDays)
|
|
408
446
|
store.authenticateBridge(bridgeId, bridgeToken)
|
|
409
|
-
const ticket = issueTicket(bridgeId, typeof email2fa === 'string' && email2fa !== '' ? email2fa : undefined)
|
|
447
|
+
const ticket = issueTicket(bridgeId, days, typeof email2fa === 'string' && email2fa !== '' ? email2fa : undefined)
|
|
410
448
|
json(res, 200, publicTicket(ticket))
|
|
411
449
|
} catch (error) { fail(res, 401, 'bridge start failed', error) }
|
|
412
450
|
return
|
|
@@ -418,7 +456,7 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
418
456
|
if (ticket === undefined || ticket.bridgeId !== bridgeId || !sameToken(ticket.refreshToken, refreshToken)) throw new Error('invalid pairing refresh token')
|
|
419
457
|
const socket = bridges.get(bridgeId)
|
|
420
458
|
if (socket?.readyState !== WebSocket.OPEN) throw new Error('bridge is offline')
|
|
421
|
-
json(res, 200, publicTicket(issueTicket(bridgeId, ticket.email2fa)))
|
|
459
|
+
json(res, 200, publicTicket(issueTicket(bridgeId, ticket.sessionDays, ticket.email2fa)))
|
|
422
460
|
} catch (error) { fail(res, 401, 'pairing rotation failed', error) }
|
|
423
461
|
return
|
|
424
462
|
}
|