@sparkelf/dsh-mobile-bridge-server 0.1.0
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 +15 -0
- package/src/index.ts +63 -0
- package/src/live.spec.ts +108 -0
- package/src/phone.ts +167 -0
- package/src/server.spec.ts +181 -0
- package/src/server.ts +252 -0
- package/src/store.spec.ts +40 -0
- package/src/store.ts +119 -0
- package/src/wechat-scheme.ts +41 -0
- package/src/wechat.spec.ts +38 -0
- package/src/wechat.ts +74 -0
package/package.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sparkelf/dsh-mobile-bridge-server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Multi-user bridge server connecting mobile browsers to local DeepSeek Harness instances through outbound tunnels.",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"dsh-mobile-bridge-server": "src/index.ts"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"nodemailer": "^6.9.0",
|
|
13
|
+
"ws": "^8.18.0"
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge server entry: reads MOBILE_BRIDGE_PORT (default 8787),
|
|
3
|
+
* MOBILE_BRIDGE_DATA (store json path), MOBILE_BRIDGE_SECRET (token HMAC
|
|
4
|
+
* secret; required, no insecure default). Email login needs SMTP_HOST,
|
|
5
|
+
* SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM; WeChat login needs
|
|
6
|
+
* WECHAT_APP_ID and WECHAT_APP_SECRET. Absent groups stay disabled.
|
|
7
|
+
* @module @sparkelf/dsh-mobile-bridge-server
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdirSync } from 'node:fs'
|
|
11
|
+
import { dirname } from 'node:path'
|
|
12
|
+
import nodemailer from 'nodemailer'
|
|
13
|
+
import { createBridgeServer } from './server.ts'
|
|
14
|
+
import { UserStore } from './store.ts'
|
|
15
|
+
import { wechatConfigFromEnv, wechatMiniprogramVerifier, wechatVerifier } from './wechat.ts'
|
|
16
|
+
|
|
17
|
+
const secret = process.env.MOBILE_BRIDGE_SECRET ?? ''
|
|
18
|
+
if (secret.length < 16) {
|
|
19
|
+
console.error('MOBILE_BRIDGE_SECRET must be at least 16 chars')
|
|
20
|
+
process.exit(1)
|
|
21
|
+
}
|
|
22
|
+
const data = process.env.MOBILE_BRIDGE_DATA ?? 'mobile-bridge-users.json'
|
|
23
|
+
mkdirSync(dirname(data) === '.' ? '.' : dirname(data), { recursive: true })
|
|
24
|
+
const port = Number(process.env.MOBILE_BRIDGE_PORT ?? 8787)
|
|
25
|
+
|
|
26
|
+
const smtpHost = (process.env.SMTP_HOST ?? '').trim()
|
|
27
|
+
const mailer = smtpHost.length > 0
|
|
28
|
+
? async (email: string, code: string) => {
|
|
29
|
+
const transport = nodemailer.createTransport({
|
|
30
|
+
host: smtpHost,
|
|
31
|
+
port: Number(process.env.SMTP_PORT ?? 465),
|
|
32
|
+
secure: Number(process.env.SMTP_PORT ?? 465) === 465,
|
|
33
|
+
...process.env.SMTP_USERNAME === undefined ? {} : {
|
|
34
|
+
auth: { user: process.env.SMTP_USERNAME, pass: process.env.SMTP_PASSWORD ?? '' },
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
await transport.sendMail({
|
|
38
|
+
from: process.env.SMTP_FROM ?? 'bridge@localhost',
|
|
39
|
+
to: email,
|
|
40
|
+
subject: 'DeepSeek Harness 登录验证码',
|
|
41
|
+
text: `您的验证码是 ${code},五分钟内有效。`,
|
|
42
|
+
})
|
|
43
|
+
await transport.close()
|
|
44
|
+
}
|
|
45
|
+
: undefined
|
|
46
|
+
if (mailer === undefined) console.log('[mobile-bridge] email login disabled (no SMTP_HOST)')
|
|
47
|
+
|
|
48
|
+
const wechat = wechatConfigFromEnv()
|
|
49
|
+
const wechatKind = (process.env.WECHAT_KIND ?? 'miniprogram').trim()
|
|
50
|
+
if (wechat === undefined) console.log('[mobile-bridge] wechat login disabled (no WECHAT_APP_ID/SECRET)')
|
|
51
|
+
|
|
52
|
+
const server = createBridgeServer(new UserStore(data, secret), {
|
|
53
|
+
...mailer === undefined ? {} : { mailer },
|
|
54
|
+
...wechat === undefined ? {} : {
|
|
55
|
+
externalAuth: {
|
|
56
|
+
wechat: wechatKind === 'open' ? wechatVerifier(wechat) : wechatMiniprogramVerifier(wechat),
|
|
57
|
+
},
|
|
58
|
+
wechatScheme: wechat,
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
server.listen(port, () => {
|
|
62
|
+
console.log(`[mobile-bridge] listening on :${port}`)
|
|
63
|
+
})
|
package/src/live.spec.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live dress rehearsal against a real local Harness web on :3080. Self-skips
|
|
3
|
+
* in CI or anywhere the loopback web is absent; on a dev box it proves the
|
|
4
|
+
* encrypted chain: phone-side crypto through the blind server pipe to the
|
|
5
|
+
* desktop relay and back, reading the real stock HTML as ciphertext on wire.
|
|
6
|
+
* @module @sparkelf/dsh-mobile-bridge-server/live
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { mkdtempSync } from 'node:fs'
|
|
10
|
+
import { createServer, type Server } from 'node:http'
|
|
11
|
+
import { AddressInfo } from 'node:net'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import WebSocket from 'ws'
|
|
15
|
+
import { afterAll, describe, expect, it } from 'vitest'
|
|
16
|
+
import { decryptJSON, deriveKey, encryptJSON } from '../../mobile-bridge/src/crypto.ts'
|
|
17
|
+
import { relayToLocalWeb, type RelayRequest } from '../../mobile-bridge/src/index.ts'
|
|
18
|
+
import { createBridgeServer } from './server.ts'
|
|
19
|
+
import { UserStore } from './store.ts'
|
|
20
|
+
|
|
21
|
+
const LIVE_PORT = Number(process.env.LIVE_HARNESS_PORT ?? 3080)
|
|
22
|
+
|
|
23
|
+
let reachable = false
|
|
24
|
+
try {
|
|
25
|
+
const probe = await fetch(`http://127.0.0.1:${LIVE_PORT}/`, { signal: AbortSignal.timeout(3000) })
|
|
26
|
+
reachable = probe.ok
|
|
27
|
+
} catch {
|
|
28
|
+
reachable = false
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let bridge: Server
|
|
32
|
+
let bridgePort: number
|
|
33
|
+
let liveCodes: string[] = []
|
|
34
|
+
|
|
35
|
+
if (reachable) {
|
|
36
|
+
const store = new UserStore(join(mkdtempSync(join(tmpdir(), 'mbs-live-')), 'u.json'), '0123456789abcdef')
|
|
37
|
+
const codes: string[] = []
|
|
38
|
+
bridge = createBridgeServer(store, { mailer: async (_email, code) => { codes.push(code) } })
|
|
39
|
+
liveCodes = codes
|
|
40
|
+
await new Promise<void>(resolve => bridge.listen(0, resolve))
|
|
41
|
+
bridgePort = (bridge.address() as AddressInfo).port
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
afterAll(async () => {
|
|
45
|
+
if (reachable) await new Promise(resolve => bridge.close(resolve))
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
describe.skipIf(!reachable)('live rehearsal against the real Harness web', () => {
|
|
49
|
+
it('reads the stock UI through the encrypted tunnel after email login', async () => {
|
|
50
|
+
const base = `http://127.0.0.1:${bridgePort}`
|
|
51
|
+
await fetch(base + '/bridge/api/email/code', {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
body: JSON.stringify({ email: 'rehearsal@example.com' }),
|
|
54
|
+
})
|
|
55
|
+
const login = await fetch(base + '/bridge/api/login/email', {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
body: JSON.stringify({ email: 'rehearsal@example.com', code: liveCodes.at(-1) ?? '' }),
|
|
58
|
+
})
|
|
59
|
+
expect(login.status).toBe(200)
|
|
60
|
+
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''
|
|
61
|
+
|
|
62
|
+
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
63
|
+
await fetch(base + '/bridge/api/bind', {
|
|
64
|
+
method: 'POST',
|
|
65
|
+
headers: { cookie, 'content-type': 'application/json' },
|
|
66
|
+
body: JSON.stringify({ bridge: start.code }),
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
const desktopKey = await deriveKey('', 'livepair')
|
|
70
|
+
const phoneKey = await deriveKey('', 'livepair')
|
|
71
|
+
const bridgeSocket = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/bridge?code=${start.code}`)
|
|
72
|
+
await new Promise<void>((resolve, reject) => { bridgeSocket.on('open', () => resolve()); bridgeSocket.on('error', reject) })
|
|
73
|
+
bridgeSocket.on('message', raw => {
|
|
74
|
+
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
75
|
+
if (wire.blob === undefined) return
|
|
76
|
+
const blobIn = wire.blob
|
|
77
|
+
void (async () => {
|
|
78
|
+
const request = await decryptJSON<RelayRequest>(desktopKey, blobIn)
|
|
79
|
+
await relayToLocalWeb({ ...request, id: wire.id }, LIVE_PORT, frame => {
|
|
80
|
+
void (async () => {
|
|
81
|
+
if (frame.end) { bridgeSocket.send(JSON.stringify({ id: frame.id, end: true })); return }
|
|
82
|
+
if (frame.stream) { bridgeSocket.send(JSON.stringify({ id: frame.id, stream: true, blob: await encryptJSON(desktopKey, { stream: true, status: frame.status, headers: frame.headers }) })); return }
|
|
83
|
+
if (frame.chunk !== undefined) { bridgeSocket.send(JSON.stringify({ id: frame.id, chunk: await encryptJSON(desktopKey, { d: frame.chunk }) })); return }
|
|
84
|
+
bridgeSocket.send(JSON.stringify({ id: frame.id, blob: await encryptJSON(desktopKey, { status: frame.status, headers: frame.headers, body: frame.body, bodyEncoding: 'base64' }) }))
|
|
85
|
+
})()
|
|
86
|
+
})
|
|
87
|
+
})()
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
const client = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/client`, { headers: { cookie } })
|
|
91
|
+
await new Promise<void>((resolve, reject) => { client.on('open', () => resolve()); client.on('error', reject) })
|
|
92
|
+
const answer = new Promise<string>(resolve => {
|
|
93
|
+
client.on('message', raw => {
|
|
94
|
+
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
95
|
+
if (wire.blob === undefined) return
|
|
96
|
+
void decryptJSON<{ body: string }>(phoneKey, wire.blob).then(full => resolve(Buffer.from(full.body, 'base64').toString('utf8')))
|
|
97
|
+
})
|
|
98
|
+
})
|
|
99
|
+
const blob = await encryptJSON(phoneKey, { method: 'GET', path: '/', headers: { accept: 'text/html' }, body: '', bodyEncoding: 'base64' })
|
|
100
|
+
client.send(JSON.stringify({ id: 'live1', blob }))
|
|
101
|
+
|
|
102
|
+
const html = await answer
|
|
103
|
+
expect(html).toContain('__DSH_BOOT__')
|
|
104
|
+
|
|
105
|
+
client.close()
|
|
106
|
+
bridgeSocket.close()
|
|
107
|
+
}, 20000)
|
|
108
|
+
})
|
package/src/phone.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phone-side bootstrap sources served verbatim by the bridge server: the
|
|
3
|
+
* service worker decrypts the end-to-end encrypted relay and serves the stock
|
|
4
|
+
* Harness web from ciphertext; the client script owns login, pairing, and SW
|
|
5
|
+
* registration. Both are plain auditable JavaScript with no secrets server-side.
|
|
6
|
+
* @module @sparkelf/dsh-mobile-bridge-server/phone
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const CRYPTO_JS = `
|
|
10
|
+
async function deriveKey(userKey, pairingSecret) {
|
|
11
|
+
const material = await crypto.subtle.importKey('raw', new TextEncoder().encode('dsh-mobile-bridge/v1:' + userKey + ':' + pairingSecret), 'HKDF', false, ['deriveKey']);
|
|
12
|
+
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('dsh-mobile-bridge'), info: new Uint8Array(0) }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
13
|
+
}
|
|
14
|
+
function bytesToBase64(bytes) { let b = ''; for (const x of bytes) b += String.fromCharCode(x); return btoa(b); }
|
|
15
|
+
function base64ToBytes(blob) { const b = atob(blob); const out = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i); return out; }
|
|
16
|
+
async function encryptJSON(key, value) {
|
|
17
|
+
const nonce = crypto.getRandomValues(new Uint8Array(12));
|
|
18
|
+
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, key, new TextEncoder().encode(JSON.stringify(value)));
|
|
19
|
+
const out = new Uint8Array(12 + ct.byteLength); out.set(nonce, 0); out.set(new Uint8Array(ct), 12);
|
|
20
|
+
return bytesToBase64(out);
|
|
21
|
+
}
|
|
22
|
+
async function decryptJSON(key, blob) {
|
|
23
|
+
const raw = base64ToBytes(blob);
|
|
24
|
+
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: raw.slice(0, 12) }, key, raw.slice(12));
|
|
25
|
+
return JSON.parse(new TextDecoder().decode(pt));
|
|
26
|
+
}
|
|
27
|
+
`
|
|
28
|
+
|
|
29
|
+
export const SW_SOURCE = `/* DSH mobile bridge service worker: blind-server E2EE client. */
|
|
30
|
+
${CRYPTO_JS}
|
|
31
|
+
let pairPromiseResolve;
|
|
32
|
+
const pairReady = new Promise(resolve => { pairPromiseResolve = resolve });
|
|
33
|
+
let keyPromise = null;
|
|
34
|
+
self.addEventListener('install', () => { self.skipWaiting() })
|
|
35
|
+
self.addEventListener('activate', event => { event.waitUntil(self.clients.claim()) })
|
|
36
|
+
self.addEventListener('message', event => {
|
|
37
|
+
if (event.data && event.data.type === 'pair') pairPromiseResolve(event.data.pair)
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
let wsPromise = null
|
|
41
|
+
let counter = 0
|
|
42
|
+
const pending = new Map()
|
|
43
|
+
|
|
44
|
+
function wsReady() {
|
|
45
|
+
if (wsPromise) return wsPromise
|
|
46
|
+
wsPromise = new Promise((resolve, reject) => {
|
|
47
|
+
const ws = new WebSocket(location.origin.replace(/^http/, 'ws') + '/ws/client')
|
|
48
|
+
ws.onopen = () => resolve(ws)
|
|
49
|
+
ws.onerror = () => { wsPromise = null; reject(new Error('bridge socket failed')) }
|
|
50
|
+
ws.onmessage = event => {
|
|
51
|
+
const frame = JSON.parse(event.data)
|
|
52
|
+
const entry = pending.get(frame.id)
|
|
53
|
+
if (!entry) return
|
|
54
|
+
if (frame.end) { entry.controller.close(); pending.delete(frame.id); return }
|
|
55
|
+
void (async () => {
|
|
56
|
+
if (frame.stream) { const head = await decryptJSON(entry.key, frame.blob); entry.status = head.status; entry.headers = head.headers; return }
|
|
57
|
+
if (frame.chunk !== undefined) { const payload = await decryptJSON(entry.key, frame.chunk); const bytes = base64ToBytes(payload.d); entry.controller.enqueue(bytes); return }
|
|
58
|
+
const full = await decryptJSON(entry.key, frame.blob)
|
|
59
|
+
let body = base64ToBytes(full.body ?? '')
|
|
60
|
+
if ((full.headers?.['content-type'] ?? '').includes('text/html')) {
|
|
61
|
+
let html = new TextDecoder().decode(body)
|
|
62
|
+
if (!html.includes('/mobile/bridge/style.css')) html = html.replace('</head>', '<link rel="stylesheet" href="/mobile/bridge/style.css"></head>')
|
|
63
|
+
body = new TextEncoder().encode(html)
|
|
64
|
+
}
|
|
65
|
+
pending.delete(frame.id)
|
|
66
|
+
entry.resolve(new Response(body, { status: full.status, headers: full.headers }))
|
|
67
|
+
})()
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
return wsPromise
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
self.addEventListener('fetch', event => {
|
|
74
|
+
const url = new URL(event.request.url)
|
|
75
|
+
if (url.pathname.startsWith('/bridge') || url.pathname === '/sw.js' || url.pathname.startsWith('/ws')) return
|
|
76
|
+
event.respondWith((async () => {
|
|
77
|
+
const pair = await pairReady
|
|
78
|
+
if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
|
|
79
|
+
const key = await keyPromise
|
|
80
|
+
const request = event.request
|
|
81
|
+
const bodyBytes = new Uint8Array(await request.arrayBuffer())
|
|
82
|
+
const id = 'r' + (++counter)
|
|
83
|
+
const blob = await encryptJSON(key, {
|
|
84
|
+
method: request.method,
|
|
85
|
+
path: url.pathname + url.search,
|
|
86
|
+
headers: { accept: request.headers.get('accept') ?? '' },
|
|
87
|
+
body: bytesToBase64(bodyBytes),
|
|
88
|
+
bodyEncoding: 'base64',
|
|
89
|
+
})
|
|
90
|
+
const ws = await wsReady()
|
|
91
|
+
if ((request.headers.get('accept') ?? '').includes('text/event-stream')) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
const controller = new TransformStream()
|
|
94
|
+
pending.set(id, { key, controller: controller.writable.getWriter(), resolve: () => resolve(new Response(controller.readable, { headers: { 'content-type': 'text/event-stream' } })), status: 200, headers: {} })
|
|
95
|
+
ws.send(JSON.stringify({ id, blob, streamHint: true }))
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
return new Promise((resolve, reject) => {
|
|
99
|
+
pending.set(id, { key, resolve, reject })
|
|
100
|
+
ws.send(JSON.stringify({ id, blob }))
|
|
101
|
+
})
|
|
102
|
+
})())
|
|
103
|
+
})
|
|
104
|
+
`
|
|
105
|
+
|
|
106
|
+
export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pairing, SW registration. */
|
|
107
|
+
(function () {
|
|
108
|
+
var $ = function (id) { return document.getElementById(id) }
|
|
109
|
+
function api(p, o) {
|
|
110
|
+
return fetch('/bridge' + p, Object.assign({ credentials: 'same-origin' }, o)).then(function (r) {
|
|
111
|
+
return r.json().then(function (j) { if (!r.ok) throw new Error(j.error || r.status); return j })
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
function registerSw(pair) {
|
|
115
|
+
if (!('serviceWorker' in navigator)) { document.querySelector('main').insertAdjacentHTML('beforeend', '<p class=err>此浏览器不支持 service worker</p>'); return }
|
|
116
|
+
navigator.serviceWorker.register('/sw.js', { scope: '/' }).then(function () {
|
|
117
|
+
return navigator.serviceWorker.ready
|
|
118
|
+
}).then(function (reg) {
|
|
119
|
+
reg.active.postMessage({ type: 'pair', pair: pair })
|
|
120
|
+
if (location.pathname !== '/') location.href = '/'
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
var fragment = location.hash.slice(1)
|
|
124
|
+
if (fragment) {
|
|
125
|
+
try {
|
|
126
|
+
var pair = JSON.parse(decodeURIComponent(fragment))
|
|
127
|
+
var proceed = function () {
|
|
128
|
+
localStorage.setItem('dshmb-pair', JSON.stringify(pair))
|
|
129
|
+
api('/api/login/bridge', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pair.b || pair.c }) })
|
|
130
|
+
.then(function (res) {
|
|
131
|
+
if (res && res.challenge === 'email') {
|
|
132
|
+
var mailCode = prompt('桌面所有者邮箱收到验证码,请输入')
|
|
133
|
+
if (mailCode === null) throw new Error('已取消')
|
|
134
|
+
return api('/api/login/bridge/verify', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pair.b || pair.c, emailCode: mailCode }) })
|
|
135
|
+
}
|
|
136
|
+
return res
|
|
137
|
+
})
|
|
138
|
+
.then(function () { history.replaceState(null, '', '/'); registerSw(pair) })
|
|
139
|
+
.catch(function (e) { var m = document.querySelector('main'); if (m) m.insertAdjacentHTML('beforeend', '<p class=err>' + e.message + '</p>') })
|
|
140
|
+
}
|
|
141
|
+
if (pair.k === undefined) {
|
|
142
|
+
var k = prompt('输入桌面端设置的加密口令')
|
|
143
|
+
if (k === null) return
|
|
144
|
+
pair.k = k
|
|
145
|
+
}
|
|
146
|
+
proceed()
|
|
147
|
+
return
|
|
148
|
+
} catch (e) { /* fall through to manual login */ }
|
|
149
|
+
}
|
|
150
|
+
var stored = localStorage.getItem('dshmb-pair')
|
|
151
|
+
if (stored && document.cookie.includes('mbs=')) { registerSw(JSON.parse(stored)); return }
|
|
152
|
+
if (!document.getElementById('e')) return
|
|
153
|
+
$('s').onclick = function () {
|
|
154
|
+
api('/api/email/code', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: $('e').value }) })
|
|
155
|
+
.then(function () { $('x').textContent = '验证码已发送' })
|
|
156
|
+
.catch(function (e) { $('x').textContent = e.message })
|
|
157
|
+
}
|
|
158
|
+
$('l').onclick = function () {
|
|
159
|
+
api('/api/login/email', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: $('e').value, code: $('c').value, bridge: $('b').value }) })
|
|
160
|
+
.then(function () {
|
|
161
|
+
var pair = JSON.parse(localStorage.getItem('dshmb-pair') || '{"s":""}')
|
|
162
|
+
registerSw(pair)
|
|
163
|
+
})
|
|
164
|
+
.catch(function (e) { $('x').textContent = e.message })
|
|
165
|
+
}
|
|
166
|
+
})()
|
|
167
|
+
`
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { mkdtempSync } from 'node:fs'
|
|
2
|
+
import { createServer, type Server } from 'node:http'
|
|
3
|
+
import { AddressInfo } from 'node:net'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import WebSocket from 'ws'
|
|
7
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
|
8
|
+
import { decryptJSON, deriveKey, encryptJSON } from '../../mobile-bridge/src/crypto.ts'
|
|
9
|
+
import { relayToLocalWeb, type RelayRequest } from '../../mobile-bridge/src/index.ts'
|
|
10
|
+
import { createBridgeServer } from './server.ts'
|
|
11
|
+
import { UserStore } from './store.ts'
|
|
12
|
+
|
|
13
|
+
let local: Server
|
|
14
|
+
let bridge: Server
|
|
15
|
+
let localPort: number
|
|
16
|
+
let bridgePort: number
|
|
17
|
+
let sentCodes: { email: string; code: string }[]
|
|
18
|
+
const wireLog: string[] = []
|
|
19
|
+
|
|
20
|
+
beforeAll(async () => {
|
|
21
|
+
local = createServer((req, res) => {
|
|
22
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
|
23
|
+
res.end('<!doctype html><head></head><body>stock web secret-marker</body>')
|
|
24
|
+
})
|
|
25
|
+
await new Promise<void>(resolve => local.listen(0, resolve))
|
|
26
|
+
localPort = (local.address() as AddressInfo).port
|
|
27
|
+
sentCodes = []
|
|
28
|
+
const store = new UserStore(join(mkdtempSync(join(tmpdir(), 'mbs-')), 'u.json'), '0123456789abcdef')
|
|
29
|
+
bridge = createBridgeServer(store, {
|
|
30
|
+
mailer: async (email, code) => { sentCodes.push({ email, code }) },
|
|
31
|
+
})
|
|
32
|
+
await new Promise<void>(resolve => bridge.listen(0, resolve))
|
|
33
|
+
bridgePort = (bridge.address() as AddressInfo).port
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
afterAll(async () => {
|
|
37
|
+
await new Promise(resolve => bridge.close(resolve))
|
|
38
|
+
await new Promise(resolve => local.close(resolve))
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
describe('bridge server end to end', () => {
|
|
42
|
+
it('emails a code, logs in, and binds', async () => {
|
|
43
|
+
const base = `http://127.0.0.1:${bridgePort}`
|
|
44
|
+
await fetch(base + '/bridge/api/email/code', { method: 'POST', body: JSON.stringify({ email: 'dee@example.com' }) })
|
|
45
|
+
const code = sentCodes.at(-1)?.code ?? ''
|
|
46
|
+
const login = await fetch(base + '/bridge/api/login/email', {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
body: JSON.stringify({ email: 'dee@example.com', code }),
|
|
49
|
+
})
|
|
50
|
+
expect(login.status).toBe(200)
|
|
51
|
+
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''
|
|
52
|
+
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
53
|
+
const bind = await fetch(base + '/bridge/api/bind', {
|
|
54
|
+
method: 'POST',
|
|
55
|
+
headers: { cookie, 'content-type': 'application/json' },
|
|
56
|
+
body: JSON.stringify({ bridge: start.code }),
|
|
57
|
+
})
|
|
58
|
+
expect(bind.status).toBe(200)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('pipes encrypted frames blindly: the phone reads the stock web, the wire stays ciphertext', async () => {
|
|
62
|
+
const base = `http://127.0.0.1:${bridgePort}`
|
|
63
|
+
await fetch(base + '/bridge/api/email/code', { method: 'POST', body: JSON.stringify({ email: 'phone@example.com' }) })
|
|
64
|
+
const code = sentCodes.at(-1)?.code ?? ''
|
|
65
|
+
const login = await fetch(base + '/bridge/api/login/email', {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
body: JSON.stringify({ email: 'phone@example.com', code }),
|
|
68
|
+
})
|
|
69
|
+
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''
|
|
70
|
+
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
71
|
+
await fetch(base + '/bridge/api/bind', {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: { cookie, 'content-type': 'application/json' },
|
|
74
|
+
body: JSON.stringify({ bridge: start.code }),
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const pairingSecret = 'deadbeef'
|
|
78
|
+
const desktopKey = await deriveKey('user-pass', pairingSecret)
|
|
79
|
+
const phoneKey = await deriveKey('user-pass', pairingSecret)
|
|
80
|
+
|
|
81
|
+
// Desktop side: decrypt phone frames, answer from the local web, encrypt back.
|
|
82
|
+
const bridgeSocket = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/bridge?code=${start.code}`)
|
|
83
|
+
await new Promise<void>((resolve, reject) => { bridgeSocket.on('open', () => resolve()); bridgeSocket.on('error', reject) })
|
|
84
|
+
bridgeSocket.on('message', raw => {
|
|
85
|
+
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
86
|
+
wireLog.push(String(raw))
|
|
87
|
+
if (wire.blob === undefined) return
|
|
88
|
+
const blobIn = wire.blob
|
|
89
|
+
void (async () => {
|
|
90
|
+
const request = await decryptJSON<RelayRequest>(desktopKey, blobIn)
|
|
91
|
+
await relayToLocalWeb({ ...request, id: wire.id }, localPort, frame => {
|
|
92
|
+
void (async () => {
|
|
93
|
+
if (frame.end) { bridgeSocket.send(JSON.stringify({ id: frame.id, end: true })); return }
|
|
94
|
+
if (frame.stream) { bridgeSocket.send(JSON.stringify({ id: frame.id, stream: true, blob: await encryptJSON(desktopKey, { stream: true, status: frame.status, headers: frame.headers }) })); return }
|
|
95
|
+
if (frame.chunk !== undefined) { bridgeSocket.send(JSON.stringify({ id: frame.id, chunk: await encryptJSON(desktopKey, { d: frame.chunk }) })); return }
|
|
96
|
+
bridgeSocket.send(JSON.stringify({ id: frame.id, blob: await encryptJSON(desktopKey, { status: frame.status, headers: frame.headers, body: frame.body, bodyEncoding: 'base64' }) }))
|
|
97
|
+
})()
|
|
98
|
+
})
|
|
99
|
+
})()
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
// Phone side (simulated service worker): encrypted request, decrypted response.
|
|
103
|
+
const client = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/client`, { headers: { cookie } })
|
|
104
|
+
await new Promise<void>((resolve, reject) => { client.on('open', () => resolve()); client.on('error', reject) })
|
|
105
|
+
const answer = new Promise<{ status: number; html: string }>(resolve => {
|
|
106
|
+
client.on('message', raw => {
|
|
107
|
+
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
108
|
+
wireLog.push(String(raw))
|
|
109
|
+
if (wire.blob === undefined) return
|
|
110
|
+
void decryptJSON<{ status: number; body: string }>(phoneKey, wire.blob).then(full => {
|
|
111
|
+
resolve({ status: full.status, html: Buffer.from(full.body, 'base64').toString('utf8') })
|
|
112
|
+
})
|
|
113
|
+
})
|
|
114
|
+
})
|
|
115
|
+
const blob = await encryptJSON(phoneKey, { method: 'GET', path: '/', headers: { accept: 'text/html' }, body: '', bodyEncoding: 'base64' })
|
|
116
|
+
client.send(JSON.stringify({ id: 'p1', blob }))
|
|
117
|
+
|
|
118
|
+
const result = await answer
|
|
119
|
+
expect(result.status).toBe(200)
|
|
120
|
+
expect(result.html).toContain('stock web secret-marker')
|
|
121
|
+
for (const line of wireLog) expect(line).not.toContain('secret-marker')
|
|
122
|
+
|
|
123
|
+
client.close()
|
|
124
|
+
bridgeSocket.close()
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('auto-logs in a phone that presents a live pairing code', async () => {
|
|
128
|
+
const base = `http://127.0.0.1:${bridgePort}`
|
|
129
|
+
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
130
|
+
const login = await fetch(base + '/bridge/api/login/bridge', {
|
|
131
|
+
method: 'POST',
|
|
132
|
+
body: JSON.stringify({ code: start.code }),
|
|
133
|
+
})
|
|
134
|
+
expect(login.status).toBe(200)
|
|
135
|
+
expect(login.headers.get('set-cookie')).toContain('mbs=')
|
|
136
|
+
const me = await fetch(base + '/bridge/api/me', { headers: { cookie: login.headers.get('set-cookie')?.split(';')[0] ?? '' } })
|
|
137
|
+
expect(await me.json()).toMatchObject({ bridge: start.code })
|
|
138
|
+
const offline = await fetch(base + '/bridge/api/login/bridge', { method: 'POST', body: JSON.stringify({ code: 'zzzzzz' }) })
|
|
139
|
+
expect(offline.status).toBe(401)
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
it('optionally challenges a scan with an owner email code', async () => {
|
|
143
|
+
const base = `http://127.0.0.1:${bridgePort}`
|
|
144
|
+
const start = await fetch(base + '/bridge/api/bridge/start', {
|
|
145
|
+
method: 'POST',
|
|
146
|
+
body: JSON.stringify({ email2fa: 'owner@example.com' }),
|
|
147
|
+
}).then(response => response.json()) as { code: string }
|
|
148
|
+
const challenged = await fetch(base + '/bridge/api/login/bridge', {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
body: JSON.stringify({ code: start.code }),
|
|
151
|
+
}).then(response => response.json()) as { challenge?: string }
|
|
152
|
+
expect(challenged.challenge).toBe('email')
|
|
153
|
+
const mail = sentCodes.filter(entry => entry.email === 'owner@example.com').at(-1)
|
|
154
|
+
const verified = await fetch(base + '/bridge/api/login/bridge/verify', {
|
|
155
|
+
method: 'POST',
|
|
156
|
+
body: JSON.stringify({ code: start.code, emailCode: mail?.code ?? '' }),
|
|
157
|
+
})
|
|
158
|
+
expect(verified.status).toBe(200)
|
|
159
|
+
expect(verified.headers.get('set-cookie')).toContain('mbs=')
|
|
160
|
+
const replay = await fetch(base + '/bridge/api/login/bridge/verify', {
|
|
161
|
+
method: 'POST',
|
|
162
|
+
body: JSON.stringify({ code: start.code, emailCode: mail?.code ?? '' }),
|
|
163
|
+
})
|
|
164
|
+
expect(replay.status).toBe(401)
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
it('rejects wrong codes and unknown providers', async () => {
|
|
168
|
+
const base = `http://127.0.0.1:${bridgePort}`
|
|
169
|
+
await fetch(base + '/bridge/api/email/code', { method: 'POST', body: JSON.stringify({ email: 'x@example.com' }) })
|
|
170
|
+
const bad = await fetch(base + '/bridge/api/login/email', {
|
|
171
|
+
method: 'POST',
|
|
172
|
+
body: JSON.stringify({ email: 'x@example.com', code: '000000' }),
|
|
173
|
+
})
|
|
174
|
+
expect(bad.status).toBe(401)
|
|
175
|
+
const unknown = await fetch(base + '/bridge/api/login/external', {
|
|
176
|
+
method: 'POST',
|
|
177
|
+
body: JSON.stringify({ provider: 'wechat', payload: { code: 'c1' } }),
|
|
178
|
+
})
|
|
179
|
+
expect(unknown.status).toBe(401)
|
|
180
|
+
})
|
|
181
|
+
})
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-user bridge server: phones and desktops authenticate with email
|
|
3
|
+
* verification codes or WeChat and bind to a pairing code. The server is a
|
|
4
|
+
* BLIND forwarder: `/ws/client` and `/ws/bridge` sockets are piped verbatim,
|
|
5
|
+
* so relayed payloads stay end-to-end encrypted between the phone service
|
|
6
|
+
* worker and the desktop plugin; the server never parses relay frames.
|
|
7
|
+
* Bridges dial OUT from the local network, so no inbound port is needed.
|
|
8
|
+
* @module @sparkelf/dsh-mobile-bridge-server/server
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { randomBytes } from 'node:crypto'
|
|
12
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
13
|
+
import { WebSocket, WebSocketServer } from 'ws'
|
|
14
|
+
import { SW_SOURCE, CLIENT_SOURCE } from './phone.ts'
|
|
15
|
+
import { UserStore } from './store.ts'
|
|
16
|
+
import type { WechatConfig } from './wechat.ts'
|
|
17
|
+
import { generateScheme } from './wechat-scheme.ts'
|
|
18
|
+
|
|
19
|
+
/** Verifies one external login payload and returns the stable identity. */
|
|
20
|
+
export type ExternalAuthVerifier = (payload: Record<string, unknown>) => Promise<string>
|
|
21
|
+
|
|
22
|
+
/** Sends one verification code email; injected so tests never touch SMTP. */
|
|
23
|
+
export type CodeMailer = (email: string, code: string) => Promise<void>
|
|
24
|
+
|
|
25
|
+
/** Options for the bridge server. */
|
|
26
|
+
export interface BridgeServerOptions {
|
|
27
|
+
/** Enabled external login providers (e.g. wechat) with their verifiers. */
|
|
28
|
+
externalAuth?: Record<string, ExternalAuthVerifier>
|
|
29
|
+
/** Delivers email verification codes; required for email login. */
|
|
30
|
+
mailer?: CodeMailer
|
|
31
|
+
/** WeChat credentials enabling URL Scheme generation for mini-program QRs. */
|
|
32
|
+
wechatScheme?: WechatConfig
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const COOKIE = 'mbs'
|
|
36
|
+
|
|
37
|
+
const LANDING = `<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>DSH Mobile Bridge</title>
|
|
38
|
+
<style>body{font:15px/1.6 system-ui,sans-serif;margin:0;background:#14161a;color:#e8eaed;display:grid;place-items:center;min-height:100vh}main{width:min(92vw,380px);background:#1d2127;border-radius:14px;padding:24px}h1{font-size:18px;margin:0 0 12px}input{width:100%;box-sizing:border-box;margin:6px 0;padding:10px;border-radius:8px;border:1px solid #333a44;background:#14161a;color:inherit}button{width:100%;margin-top:10px;padding:10px;border:0;border-radius:8px;background:#4c8dff;color:#fff;font-weight:600}button.ghost{background:#2a3038}p.err{color:#ff8080;min-height:1.2em}</style>
|
|
39
|
+
<main><h1>DeepSeek Harness Mobile</h1><input id=e type=email placeholder=邮箱><div style=display:flex;gap:8px><input id=c placeholder=验证码 style=margin:6px 0><button id=s class=ghost style=margin:6px 0;width:40%>发送</button></div><input id=b placeholder=绑定码(扫码可免填)><p class=err id=x></p><button id=l>登录并连接</button></main>
|
|
40
|
+
<script src="/bridge/client.js"></script>`
|
|
41
|
+
|
|
42
|
+
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
43
|
+
res.writeHead(status, { 'content-type': 'application/json' })
|
|
44
|
+
res.end(JSON.stringify(body))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function readBody(req: IncomingMessage): Promise<string> {
|
|
48
|
+
const chunks: Buffer[] = []
|
|
49
|
+
for await (const chunk of req) chunks.push(chunk as Buffer)
|
|
50
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function cookieToken(req: IncomingMessage): string {
|
|
54
|
+
const header = req.headers.cookie ?? ''
|
|
55
|
+
const match = header.match(new RegExp('(?:^|; )' + COOKIE + '=([^;]+)'))
|
|
56
|
+
return match ? decodeURIComponent(match[1]) : ''
|
|
57
|
+
}
|
|
58
|
+
|
|
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
|
+
/** Options for the bridge server. */
|
|
67
|
+
export interface BridgeServerRuntimeOptions extends BridgeServerOptions {
|
|
68
|
+
/** Pairing login ticket lifetime; defaults to five minutes. */
|
|
69
|
+
ticketTtlMs?: number
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function createBridgeServer(store: UserStore, options: BridgeServerRuntimeOptions = {}) {
|
|
73
|
+
const externalAuth = options.externalAuth ?? {}
|
|
74
|
+
const mailer = options.mailer
|
|
75
|
+
const ticketTtlMs = options.ticketTtlMs ?? 5 * 60_000
|
|
76
|
+
const bridges = new Map<string, WebSocket>()
|
|
77
|
+
const tickets = new Map<string, { createdAt: number; used: boolean; email2fa?: string }>()
|
|
78
|
+
|
|
79
|
+
const http = createServer((req, res) => {
|
|
80
|
+
void (async () => {
|
|
81
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
82
|
+
if (url.pathname === '/bridge' || url.pathname === '/bridge/') {
|
|
83
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
|
84
|
+
res.end(LANDING)
|
|
85
|
+
return
|
|
86
|
+
}
|
|
87
|
+
if (url.pathname === '/bridge/client.js') {
|
|
88
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
89
|
+
res.end(CLIENT_SOURCE)
|
|
90
|
+
return
|
|
91
|
+
}
|
|
92
|
+
if (url.pathname === '/sw.js') {
|
|
93
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store', 'service-worker-allowed': '/' })
|
|
94
|
+
res.end(SW_SOURCE)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/email/code') {
|
|
98
|
+
if (mailer === undefined) { json(res, 503, { error: 'email login not configured' }); return }
|
|
99
|
+
try {
|
|
100
|
+
const { email } = JSON.parse(await readBody(req)) as { email: string }
|
|
101
|
+
const code = store.issueEmailCode(email)
|
|
102
|
+
await mailer(email, code)
|
|
103
|
+
json(res, 200, { sent: true })
|
|
104
|
+
} catch (error) { json(res, 400, { error: error instanceof Error ? error.message : String(error) }) }
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/login/email') {
|
|
108
|
+
try {
|
|
109
|
+
const { email, code, bridge } = JSON.parse(await readBody(req)) as { email: string; code: string; bridge?: string }
|
|
110
|
+
store.consumeEmailCode(email, code)
|
|
111
|
+
const token = store.loginExternal('email', email.trim().toLowerCase())
|
|
112
|
+
if (typeof bridge === 'string' && bridge.trim().length > 0) store.bind(token, bridge)
|
|
113
|
+
res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': [`${COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/`] })
|
|
114
|
+
res.end(JSON.stringify({ token }))
|
|
115
|
+
} catch (error) { json(res, 401, { error: error instanceof Error ? error.message : String(error) }) }
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/login/external') {
|
|
119
|
+
try {
|
|
120
|
+
const { provider, payload } = JSON.parse(await readBody(req)) as { provider: string; payload: Record<string, unknown> }
|
|
121
|
+
const verify = externalAuth[provider]
|
|
122
|
+
if (!verify) throw new Error('unknown provider')
|
|
123
|
+
const externalId = await verify(payload ?? {})
|
|
124
|
+
const token = store.loginExternal(provider, externalId)
|
|
125
|
+
res.writeHead(200, { 'content-type': 'application/json', 'set-cookie': [`${COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/`] })
|
|
126
|
+
res.end(JSON.stringify({ token }))
|
|
127
|
+
} catch (error) { json(res, 401, { error: error instanceof Error ? error.message : String(error) }) }
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
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
|
+
try {
|
|
134
|
+
const { code } = JSON.parse(await readBody(req)) as { code: string }
|
|
135
|
+
const ticket = tickets.get(code)
|
|
136
|
+
if (ticket === undefined || !bridges.has(code)) throw new Error('unknown or offline pairing code')
|
|
137
|
+
if (ticket.used) throw new Error('pairing code already used')
|
|
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.
|
|
141
|
+
await mailer(ticket.email2fa, store.issueEmailCode(ticket.email2fa))
|
|
142
|
+
json(res, 200, { challenge: 'email' })
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
ticket.used = true
|
|
146
|
+
const token = store.loginExternal('bridge', code)
|
|
147
|
+
store.bind(token, code)
|
|
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) }) }
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/login/bridge/verify') {
|
|
154
|
+
try {
|
|
155
|
+
const { code, emailCode } = JSON.parse(await readBody(req)) as { code: string; emailCode: string }
|
|
156
|
+
const ticket = tickets.get(code)
|
|
157
|
+
if (ticket === undefined || !bridges.has(code) || ticket.email2fa === undefined) throw new Error('no pending challenge')
|
|
158
|
+
if (ticket.used) throw new Error('pairing code already used')
|
|
159
|
+
if (Date.now() - ticket.createdAt > ticketTtlMs) throw new Error('pairing code expired')
|
|
160
|
+
store.consumeEmailCode(ticket.email2fa, emailCode)
|
|
161
|
+
ticket.used = true
|
|
162
|
+
const token = store.loginExternal('bridge', code)
|
|
163
|
+
store.bind(token, code)
|
|
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) }) }
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
const token = cookieToken(req) || (req.headers.authorization ?? '').replace(/^Bearer /, '')
|
|
170
|
+
if (req.method === 'GET' && url.pathname === '/bridge/api/me') {
|
|
171
|
+
const name = store.userFor(token)
|
|
172
|
+
if (!name) { json(res, 401, { error: 'unknown token' }); return }
|
|
173
|
+
json(res, 200, { name, bridge: store.bridgeFor(token) })
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/bind') {
|
|
177
|
+
try {
|
|
178
|
+
const { bridge } = JSON.parse(await readBody(req)) as { bridge: string }
|
|
179
|
+
json(res, 200, { name: store.bind(token, bridge) })
|
|
180
|
+
} catch (error) { json(res, 400, { error: error instanceof Error ? error.message : String(error) }) }
|
|
181
|
+
return
|
|
182
|
+
}
|
|
183
|
+
if (req.method === 'GET' && url.pathname === '/bridge/wxauth') {
|
|
184
|
+
// Mini-program web-view entry: wx.login code plus optional pairing.
|
|
185
|
+
const code = url.searchParams.get('code') ?? ''
|
|
186
|
+
const pair = url.searchParams.get('pair') ?? ''
|
|
187
|
+
const verify = externalAuth.wechat
|
|
188
|
+
if (verify === undefined) { json(res, 503, { error: 'wechat not configured' }); return }
|
|
189
|
+
try {
|
|
190
|
+
const externalId = await verify({ code })
|
|
191
|
+
const token = store.loginExternal('wechat', externalId)
|
|
192
|
+
if (pair.length > 0) store.bind(token, pair)
|
|
193
|
+
res.writeHead(302, {
|
|
194
|
+
'set-cookie': [`${COOKIE}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/`],
|
|
195
|
+
location: '/',
|
|
196
|
+
})
|
|
197
|
+
res.end()
|
|
198
|
+
} catch (error) { json(res, 401, { error: error instanceof Error ? error.message : String(error) }) }
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/scheme') {
|
|
202
|
+
if (options.wechatScheme === undefined) { json(res, 503, { error: 'wechat not configured' }); return }
|
|
203
|
+
try {
|
|
204
|
+
const { query } = JSON.parse(await readBody(req)) as { query: string }
|
|
205
|
+
const openlink = await generateScheme(options.wechatScheme, String(query ?? '').slice(0, 512))
|
|
206
|
+
json(res, 200, { openlink })
|
|
207
|
+
} catch (error) { json(res, 502, { error: error instanceof Error ? error.message : String(error) }) }
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
if (req.method === 'POST' && url.pathname === '/bridge/api/bridge/start') {
|
|
211
|
+
const { email2fa } = JSON.parse(await readBody(req) || '{}') as { email2fa?: string }
|
|
212
|
+
const code = randomBytes(3).toString('hex')
|
|
213
|
+
bridges.set(code, null as unknown as WebSocket)
|
|
214
|
+
tickets.set(code, { createdAt: Date.now(), used: false, ...typeof email2fa === 'string' && email2fa.length > 0 ? { email2fa } : {} })
|
|
215
|
+
json(res, 200, { code })
|
|
216
|
+
return
|
|
217
|
+
}
|
|
218
|
+
json(res, 404, { error: 'not found' })
|
|
219
|
+
})()
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
const wss = new WebSocketServer({ noServer: true })
|
|
223
|
+
http.on('upgrade', (req, socket, head) => {
|
|
224
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
225
|
+
if (url.pathname === '/ws/bridge') {
|
|
226
|
+
const code = url.searchParams.get('code') ?? ''
|
|
227
|
+
if (!bridges.has(code)) { socket.destroy(); return }
|
|
228
|
+
wss.handleUpgrade(req, socket, head, ws => {
|
|
229
|
+
bridges.set(code, ws)
|
|
230
|
+
ws.on('close', () => { if (bridges.get(code) === ws) bridges.delete(code) })
|
|
231
|
+
})
|
|
232
|
+
return
|
|
233
|
+
}
|
|
234
|
+
if (url.pathname === '/ws/client') {
|
|
235
|
+
const token = url.searchParams.get('token') ?? cookieToken(req)
|
|
236
|
+
const bridge = store.bridgeFor(token)
|
|
237
|
+
const bridgeSocket = bridge ? bridges.get(bridge) : undefined
|
|
238
|
+
if (!bridge || !bridgeSocket || bridgeSocket.readyState !== WebSocket.OPEN) { socket.destroy(); return }
|
|
239
|
+
wss.handleUpgrade(req, socket, head, client => {
|
|
240
|
+
// Blind pipe: raw frames only, never parsed.
|
|
241
|
+
client.on('message', raw => { if (bridgeSocket.readyState === WebSocket.OPEN) bridgeSocket.send(raw.toString()) })
|
|
242
|
+
bridgeSocket.on('message', raw => { if (client.readyState === WebSocket.OPEN) client.send(raw.toString()) })
|
|
243
|
+
const detach = () => { bridgeSocket.removeAllListeners('message') }
|
|
244
|
+
client.on('close', detach)
|
|
245
|
+
})
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
socket.destroy()
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
return http
|
|
252
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { mkdtempSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { tmpdir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { describe, expect, it } from 'vitest'
|
|
5
|
+
import { UserStore } from './store.ts'
|
|
6
|
+
|
|
7
|
+
function freshStore() {
|
|
8
|
+
const file = join(mkdtempSync(join(tmpdir(), 'mbs-')), 'users.json')
|
|
9
|
+
return new UserStore(file, '0123456789abcdef')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
describe('user store', () => {
|
|
13
|
+
it('issues and consumes email codes once', () => {
|
|
14
|
+
const store = freshStore()
|
|
15
|
+
const code = store.issueEmailCode('Dee@Example.com')
|
|
16
|
+
expect(code).toMatch(/^\d{6}$/)
|
|
17
|
+
store.consumeEmailCode('dee@example.com', code)
|
|
18
|
+
expect(() => store.consumeEmailCode('dee@example.com', code)).toThrow(/invalid/)
|
|
19
|
+
expect(() => store.issueEmailCode('not-an-email')).toThrow(/invalid email/)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('logs in external providers and creates the user on first sight', () => {
|
|
23
|
+
const store = freshStore()
|
|
24
|
+
const token = store.loginExternal('wechat', 'wx-open-1')
|
|
25
|
+
expect(store.userFor(token)).toBe('wechat:wx-open-1')
|
|
26
|
+
const emailToken = store.loginExternal('email', 'dee@example.com')
|
|
27
|
+
expect(store.userFor(emailToken)).toBe('email:dee@example.com')
|
|
28
|
+
store.bind(token, 'ff00ff')
|
|
29
|
+
expect(store.bridgeFor(token)).toBe('ff00ff')
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('persists across instances via the json file', () => {
|
|
33
|
+
const file = join(mkdtempSync(join(tmpdir(), 'mbs-')), 'users.json')
|
|
34
|
+
writeFileSync(file, JSON.stringify({ users: {}, tokens: {}, codes: {} }))
|
|
35
|
+
const first = new UserStore(file, '0123456789abcdef')
|
|
36
|
+
first.loginExternal('email', 'carol@example.com')
|
|
37
|
+
const second = new UserStore(file, '0123456789abcdef')
|
|
38
|
+
expect(second.loginExternal('email', 'carol@example.com')).toBeTruthy()
|
|
39
|
+
})
|
|
40
|
+
})
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency user store: identities are email addresses or external
|
|
3
|
+
* provider ids (WeChat), never passwords; HMAC session tokens; user-to-bridge
|
|
4
|
+
* bindings; and short-lived email verification codes. Persisted as one JSON
|
|
5
|
+
* document with atomic replacement.
|
|
6
|
+
* @module @sparkelf/dsh-mobile-bridge-server/store
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createHash, createHmac, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'
|
|
10
|
+
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/** One registered user record, keyed by provider plus external id. */
|
|
14
|
+
export interface UserRecord {
|
|
15
|
+
key: string
|
|
16
|
+
provider: string
|
|
17
|
+
externalId: string
|
|
18
|
+
bridge: string | null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One pending email verification code. */
|
|
22
|
+
interface CodeRecord {
|
|
23
|
+
code: string
|
|
24
|
+
expiresAt: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Persisted store document. */
|
|
28
|
+
interface StoreDocument {
|
|
29
|
+
users: Record<string, UserRecord>
|
|
30
|
+
tokens: Record<string, string>
|
|
31
|
+
codes: Record<string, CodeRecord>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Verification code lifetime in milliseconds. */
|
|
35
|
+
export const CODE_TTL_MS = 5 * 60_000
|
|
36
|
+
|
|
37
|
+
/** File-backed user/token store with atomic writes. */
|
|
38
|
+
export class UserStore {
|
|
39
|
+
private doc: StoreDocument
|
|
40
|
+
|
|
41
|
+
constructor(private file: string, private tokenSecret: string) {
|
|
42
|
+
try {
|
|
43
|
+
this.doc = JSON.parse(readFileSync(file, 'utf8')) as StoreDocument
|
|
44
|
+
} catch {
|
|
45
|
+
this.doc = { users: {}, tokens: {}, codes: {} }
|
|
46
|
+
}
|
|
47
|
+
this.doc.codes ??= {}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private save(): void {
|
|
51
|
+
const tmp = join(this.file + '.tmp')
|
|
52
|
+
writeFileSync(tmp, JSON.stringify(this.doc, null, 2) + '\n', { mode: 0o600 })
|
|
53
|
+
renameSync(tmp, this.file)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private mintToken(key: string): string {
|
|
57
|
+
const token = createHmac('sha256', this.tokenSecret).update(key + ':' + randomBytes(8).toString('hex')).digest('hex')
|
|
58
|
+
this.doc.tokens[token] = key
|
|
59
|
+
this.save()
|
|
60
|
+
return token
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Mint a six-digit verification code for one email, replacing any pending one. */
|
|
64
|
+
issueEmailCode(email: string): string {
|
|
65
|
+
const key = email.trim().toLowerCase()
|
|
66
|
+
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(key)) throw new Error('invalid email')
|
|
67
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, '0')
|
|
68
|
+
this.doc.codes[key] = { code, expiresAt: Date.now() + CODE_TTL_MS }
|
|
69
|
+
this.save()
|
|
70
|
+
return code
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Verify and consume one email code; wrong or expired codes fail loudly. */
|
|
74
|
+
consumeEmailCode(email: string, code: string): void {
|
|
75
|
+
const key = email.trim().toLowerCase()
|
|
76
|
+
const pending = this.doc.codes[key]
|
|
77
|
+
const expected = Buffer.from(pending?.code ?? '------')
|
|
78
|
+
const attempt = Buffer.from(code.padEnd(6, '-'))
|
|
79
|
+
const valid = pending !== undefined && pending.expiresAt > Date.now()
|
|
80
|
+
&& expected.length === attempt.length && timingSafeEqual(expected, attempt)
|
|
81
|
+
if (!valid) throw new Error('invalid or expired code')
|
|
82
|
+
delete this.doc.codes[key]
|
|
83
|
+
this.save()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Log in through a verified identity, creating the user on first sight. */
|
|
87
|
+
loginExternal(provider: string, externalId: string): string {
|
|
88
|
+
const key = provider + ':' + externalId
|
|
89
|
+
if (!this.doc.users[key]) {
|
|
90
|
+
this.doc.users[key] = { key, provider, externalId, bridge: null }
|
|
91
|
+
}
|
|
92
|
+
return this.mintToken(key)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Resolve a session token to its user key. */
|
|
96
|
+
userFor(token: string): string | undefined {
|
|
97
|
+
return this.doc.tokens[token]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Bind a user to a bridge code. */
|
|
101
|
+
bind(token: string, bridge: string): string {
|
|
102
|
+
const key = this.userFor(token)
|
|
103
|
+
if (!key) throw new Error('unknown token')
|
|
104
|
+
this.doc.users[key].bridge = bridge.trim()
|
|
105
|
+
this.save()
|
|
106
|
+
return key
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The bridge code a user is bound to. */
|
|
110
|
+
bridgeFor(token: string): string | null {
|
|
111
|
+
const key = this.userFor(token)
|
|
112
|
+
return key ? this.doc.users[key].bridge : null
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Stable fingerprint for integrity checks in tests. */
|
|
116
|
+
fingerprint(): string {
|
|
117
|
+
return createHash('sha256').update(JSON.stringify(this.doc)).digest('hex').slice(0, 12)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WeChat URL Scheme generation so scanning a QR with WeChat opens the bridge
|
|
3
|
+
* mini program with the pairing query. Access tokens are cached until shortly
|
|
4
|
+
* before expiry.
|
|
5
|
+
* @module @sparkelf/dsh-mobile-bridge-server/wechat-scheme
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { WechatConfig } from './wechat.ts'
|
|
9
|
+
|
|
10
|
+
interface TokenCache {
|
|
11
|
+
token: string
|
|
12
|
+
expiresAt: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
let cache: TokenCache | undefined
|
|
16
|
+
|
|
17
|
+
/** Fetch (or reuse) the client-credential access token. */
|
|
18
|
+
export async function accessToken(config: WechatConfig, fetchImpl: typeof fetch = fetch): Promise<string> {
|
|
19
|
+
if (cache !== undefined && cache.expiresAt > Date.now() + 60_000) return cache.token
|
|
20
|
+
const url = 'https://api.weixin.qq.com/cgi-bin/token'
|
|
21
|
+
+ `?grant_type=client_credential&appid=${encodeURIComponent(config.appId)}&secret=${encodeURIComponent(config.appSecret)}`
|
|
22
|
+
const response = await fetchImpl(url)
|
|
23
|
+
const body = await response.json() as { access_token?: string; expires_in?: number; errcode?: number; errmsg?: string }
|
|
24
|
+
if (!body.access_token) throw new Error('wechat token: ' + String(body.errcode ?? 'missing'))
|
|
25
|
+
cache = { token: body.access_token, expiresAt: Date.now() + (body.expires_in ?? 7200) * 1000 }
|
|
26
|
+
return cache.token
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Generate a URL Scheme that opens the mini program at pages/bridge with query. */
|
|
30
|
+
export async function generateScheme(config: WechatConfig, query: string, fetchImpl: typeof fetch = fetch): Promise<string> {
|
|
31
|
+
const token = await accessToken(config, fetchImpl)
|
|
32
|
+
const response = await fetchImpl(`https://api.weixin.qq.com/wxa/generatescheme?access_token=${encodeURIComponent(token)}`, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: { 'content-type': 'application/json' },
|
|
35
|
+
body: JSON.stringify({ jump_wxa: { path: 'pages/bridge/bridge', query, expire_type: 1, expire_interval: 30 } }),
|
|
36
|
+
})
|
|
37
|
+
const body = await response.json() as { errcode?: number; errmsg?: string; openlink?: string }
|
|
38
|
+
if (body.errcode) throw new Error('wechat scheme: ' + (body.errmsg ?? String(body.errcode)))
|
|
39
|
+
if (!body.openlink) throw new Error('wechat scheme: missing openlink')
|
|
40
|
+
return body.openlink
|
|
41
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
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
|
+
})
|
package/src/wechat.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WeChat open-platform web login verifier: exchanges the QR-login `code` for
|
|
3
|
+
* an access token and returns the stable openid (unionid when present) as
|
|
4
|
+
* the external identity. Enabled only when WECHAT_APP_ID and
|
|
5
|
+
* WECHAT_APP_SECRET are configured; otherwise the provider stays absent.
|
|
6
|
+
* @module @sparkelf/dsh-mobile-bridge-server/wechat
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ExternalAuthVerifier } from './server.ts'
|
|
10
|
+
|
|
11
|
+
/** WeChat open-platform credentials for one deployment. */
|
|
12
|
+
export interface WechatConfig {
|
|
13
|
+
appId: string
|
|
14
|
+
appSecret: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Build a WeChat verifier from config; fetch seam injectable for tests. */
|
|
18
|
+
export function wechatVerifier(
|
|
19
|
+
config: WechatConfig,
|
|
20
|
+
fetchImpl: typeof fetch = fetch,
|
|
21
|
+
): ExternalAuthVerifier {
|
|
22
|
+
return async payload => {
|
|
23
|
+
const code = String(payload.code ?? '').trim()
|
|
24
|
+
if (code.length === 0) throw new Error('missing wechat code')
|
|
25
|
+
const url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
|
|
26
|
+
+ `?appid=${encodeURIComponent(config.appId)}`
|
|
27
|
+
+ `&secret=${encodeURIComponent(config.appSecret)}`
|
|
28
|
+
+ `&code=${encodeURIComponent(code)}`
|
|
29
|
+
+ '&grant_type=authorization_code'
|
|
30
|
+
const response = await fetchImpl(url)
|
|
31
|
+
const token = await response.json() as { errcode?: number; errmsg?: string; openid?: string; unionid?: string }
|
|
32
|
+
if (token.errcode) throw new Error('wechat: ' + (token.errmsg ?? String(token.errcode)))
|
|
33
|
+
const identity = token.unionid ?? token.openid
|
|
34
|
+
if (!identity) throw new Error('wechat: no stable identity in token response')
|
|
35
|
+
return identity
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Mini-program bridge verifier: exchanges a wx.login `code` through
|
|
41
|
+
* jscode2session for the stable openid (unionid when present). The mini
|
|
42
|
+
* program is a thin shell whose web-view consumes the resulting session.
|
|
43
|
+
* @param config - mini program appId/appSecret.
|
|
44
|
+
* @param fetchImpl - fetch seam for tests.
|
|
45
|
+
* @returns verifier for the external login seam.
|
|
46
|
+
*/
|
|
47
|
+
export function wechatMiniprogramVerifier(
|
|
48
|
+
config: WechatConfig,
|
|
49
|
+
fetchImpl: typeof fetch = fetch,
|
|
50
|
+
): ExternalAuthVerifier {
|
|
51
|
+
return async payload => {
|
|
52
|
+
const code = String(payload.code ?? '').trim()
|
|
53
|
+
if (code.length === 0) throw new Error('missing wechat code')
|
|
54
|
+
const url = 'https://api.weixin.qq.com/sns/jscode2session'
|
|
55
|
+
+ `?appid=${encodeURIComponent(config.appId)}`
|
|
56
|
+
+ `&secret=${encodeURIComponent(config.appSecret)}`
|
|
57
|
+
+ `&js_code=${encodeURIComponent(code)}`
|
|
58
|
+
+ '&grant_type=authorization_code'
|
|
59
|
+
const response = await fetchImpl(url)
|
|
60
|
+
const session = await response.json() as { errcode?: number; errmsg?: string; openid?: string; unionid?: string }
|
|
61
|
+
if (session.errcode) throw new Error('wechat: ' + (session.errmsg ?? String(session.errcode)))
|
|
62
|
+
const identity = session.unionid ?? session.openid
|
|
63
|
+
if (!identity) throw new Error('wechat: no stable identity in jscode2session response')
|
|
64
|
+
return identity
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Read WeChat config from env; undefined disables the provider. */
|
|
69
|
+
export function wechatConfigFromEnv(env: NodeJS.ProcessEnv = process.env): WechatConfig | undefined {
|
|
70
|
+
const appId = (env.WECHAT_APP_ID ?? '').trim()
|
|
71
|
+
const appSecret = (env.WECHAT_APP_SECRET ?? '').trim()
|
|
72
|
+
if (!appId || !appSecret) return undefined
|
|
73
|
+
return { appId, appSecret }
|
|
74
|
+
}
|