@yusho/server 0.1.16 → 0.1.18
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/app/lanxfer.mjs +5 -5
- package/app/launcher.mjs +6 -2
- package/app/net.mjs +1 -1
- package/app/p2plink.mjs +142 -132
- package/connector/lib/connector.mjs +3 -3
- package/connector/lib/lanfile.mjs +2 -2
- package/node_modules/@local/yusho-pc/lib/client.js +10 -10
- package/package.json +1 -1
- package/run.mjs +3 -1
package/app/lanxfer.mjs
CHANGED
|
@@ -11,7 +11,7 @@ const seal = (key, i, plain) => { const c = crypto.createCipheriv('aes-256-gcm',
|
|
|
11
11
|
const open = (key, i, s) => { const d = crypto.createDecipheriv('aes-256-gcm', key, nonceOf(i)); d.setAuthTag(s.subarray(s.length - 16)); return Buffer.concat([d.update(s.subarray(0, s.length - 16)), d.final()]) }
|
|
12
12
|
const fileSha = (p) => new Promise((ok, no) => { const h = crypto.createHash('sha256'); fs.createReadStream(p).on('data', (d) => h.update(d)).on('end', () => ok(h.digest('hex'))).on('error', no) })
|
|
13
13
|
|
|
14
|
-
const RELAY_MAX = 100 * 1024 * 1024 //
|
|
14
|
+
const RELAY_MAX = 100 * 1024 * 1024 // 远程直连没连上、只能经服务器中转时,最多传 100 MB(服务器带宽小)
|
|
15
15
|
// 电脑主动发来(file.push,12-03):acceptPush 只在手机上开;pcOf(pk) 认得是自己的电脑才收;
|
|
16
16
|
// askPush({ name, size, pc, id }) → true 直接收 / false 先挂着等用户点“收下”(比如用流量又超过 100 MB);收完调 onReceived(view)
|
|
17
17
|
export function createLanXfer({ workspace, send, log = () => {}, changed = () => {}, p2p = null, acceptPush = false, pcOf = () => null, askPush = async () => true, onReceived = () => {} }) {
|
|
@@ -35,7 +35,7 @@ export function createLanXfer({ workspace, send, log = () => {}, changed = () =>
|
|
|
35
35
|
if (m.type === 'file.lan') { (waits.get(m.req ?? m.id) ?? waits.get(m.id))?.(m); return }
|
|
36
36
|
if (m.type === 'file.saved' || m.type === 'file.failed') { if (m.req && waits.has(m.req)) return waits.get(m.req)(m); if (waits.has(m.id)) return waits.get(m.id)(m); finals.get(m.id)?.(m) }
|
|
37
37
|
}
|
|
38
|
-
/** 传输通道:同一个局域网走 HTTP
|
|
38
|
+
/** 传输通道:同一个局域网走 HTTP(最快);连不上就远程直连(文件不经过服务器);远程直连也只能走中转时,大文件不传 */
|
|
39
39
|
async function transport(lan, pc, x) {
|
|
40
40
|
try {
|
|
41
41
|
const base = await pickUrl(lan)
|
|
@@ -44,16 +44,16 @@ export function createLanXfer({ workspace, send, log = () => {}, changed = () =>
|
|
|
44
44
|
put: async (i, body) => { const r = await fetch(base + '/' + i + '?t=' + lan.token, { method: 'PUT', body, signal: AbortSignal.timeout(60_000) }); if (!r.ok) throw new Error('HTTP ' + r.status) }, close: () => {} }
|
|
45
45
|
} catch (lanErr) {
|
|
46
46
|
if (!p2p || !lan.id) throw lanErr
|
|
47
|
-
upd(x, { state: '
|
|
47
|
+
upd(x, { state: '不在同一个网络,远程直连…' })
|
|
48
48
|
let link
|
|
49
|
-
try { link = await p2p.open(pc.pk) } catch (e) { throw new Error('
|
|
49
|
+
try { link = await p2p.open(pc.pk) } catch (e) { throw new Error('不在同一个网络,远程直连也没连上(' + e.message + ')。回到同一个 Wi-Fi 再传') }
|
|
50
50
|
if (link.route === 'relay' && (x.size || lan.size || 0) > RELAY_MAX) { link.close(); throw new Error('两边网络都不让直连,只能经服务器中转,文件超过 100 MB 不走中转。回到同一个 Wi-Fi 再传') }
|
|
51
51
|
const call = async (head, body) => { const r = await link.request({ id: lan.id, t: lan.token, ...head }, body ?? null, 90_000); if (r.head.code !== 200) throw new Error(r.head.error || 'HTTP ' + r.head.code); return r }
|
|
52
52
|
return { route: link.route === 'relay' ? 'relay' : 'p2p', status: async () => (await call({ op: 'status' })).head,
|
|
53
53
|
get: async (i) => (await call({ op: 'get', i })).body, put: async (i, body) => { await call({ op: 'put', i }, body) }, close: () => link.close() }
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
-
const ROUTE_ZH = { lan: '局域网直连', p2p: '
|
|
56
|
+
const ROUTE_ZH = { lan: '局域网直连', p2p: '远程直连', relay: '经服务器中转' }
|
|
57
57
|
async function pool(n, items, fn) { let i = 0; await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (i < items.length) { const k = items[i++]; await fn(k) } })) }
|
|
58
58
|
|
|
59
59
|
/** 把 App 工作目录里的一个文件发给电脑 */
|
package/app/launcher.mjs
CHANGED
|
@@ -600,9 +600,9 @@ if (PC && WF_CWD) {
|
|
|
600
600
|
srv.listen(PC_TOOLS_PORT, '127.0.0.1', () => log('[网站和工具] 本机预览 http://127.0.0.1:' + PC_TOOLS_PORT))
|
|
601
601
|
}
|
|
602
602
|
// 手机 ↔ 电脑直连传文件(同一个 Wi-Fi 时不走服务器)
|
|
603
|
-
//
|
|
603
|
+
// 不在同一个网络:远程直连(p2plink.mjs,12-03)。信令走端到端加密消息,通行证向号码服务要
|
|
604
604
|
const P2P = createP2PLink({ send: (pk, o) => net.sendTo(pk, o), iceServers: () => net.turnCreds(), log })
|
|
605
|
-
setTimeout(() => p2pAvailable().then((ok) => log('
|
|
605
|
+
setTimeout(() => p2pAvailable().then((ok) => log('远程直连:' + (ok ? '可用' : '这台设备不可用(没有 node-datachannel 原生库),只走局域网和服务器中转。原因:' + (p2pError() ?? '未知'))), () => {}), 3000) // 手机上看日志就知道原生库装没装上
|
|
606
606
|
// 手机现在的网络(安卓外壳告诉内核:后台服务收消息时带上,网络一变也马上报):cell 流量 / wifi,metered 按流量计费
|
|
607
607
|
const NETSTATE = { cell: false, metered: false, at: 0 }
|
|
608
608
|
const setNet = (q) => { const v = String(q ?? ''); if (!/^[cw][mu]$/.test(v)) return; const was = NETSTATE.metered; NETSTATE.cell = v[0] === 'c'; NETSTATE.metered = v[1] === 'm'; NETSTATE.at = Date.now(); if (was !== NETSTATE.metered) log('网络:' + (NETSTATE.cell ? '流量' : 'Wi-Fi') + (NETSTATE.metered ? '(按流量计费)' : '')) }
|
|
@@ -1755,6 +1755,10 @@ http.createServer((req, res) => {
|
|
|
1755
1755
|
if (LOCAL_SECRET && req.headers['x-shoal-secret'] !== LOCAL_SECRET) { res.writeHead(403); return res.end('forbidden') }
|
|
1756
1756
|
if (req.url === '/api/ui-url') return json(res, 200, { url: uiUrl })
|
|
1757
1757
|
handle(req, res)
|
|
1758
|
+
}).on('error', (e) => {
|
|
1759
|
+
// 端口被占等:不让整个进程退出。手机界面走 __shoalApi 不靠这个端口,照样初始化
|
|
1760
|
+
log('本机服务起不来(' + (e?.code || e?.message) + '),端口 ' + PORT + ';界面仍可经内置通道使用')
|
|
1761
|
+
if (ready() && !inited) init().catch((e2) => log('初始化失败:', e2?.message))
|
|
1758
1762
|
}).listen(PORT, '127.0.0.1', () => { log('本机服务 http://127.0.0.1:' + PORT); if (ready()) init().catch((e) => log('初始化失败:', e?.message)); reportBack().catch(() => {}) })
|
|
1759
1763
|
async function handle(req, res) {
|
|
1760
1764
|
try {
|
package/app/net.mjs
CHANGED
|
@@ -522,7 +522,7 @@ export async function openNet({ dir, filesDir = path.join(dir, 'files'), relayUr
|
|
|
522
522
|
report: taskReport,
|
|
523
523
|
social,
|
|
524
524
|
setNotifier(f) { notifier = f },
|
|
525
|
-
/**
|
|
525
|
+
/** 远程直连的通行证(STUN / TURN,一小时有效):向号码服务要,快过期才重新要;没开或连不上返回 null,只用公共 STUN */
|
|
526
526
|
async turnCreds() {
|
|
527
527
|
if (turnCache && turnCache.exp - Date.now() > 10 * 60_000) return turnCache.c
|
|
528
528
|
const url = idService.replace(/\/$/, '') + '/api/id/turn'
|
package/app/p2plink.mjs
CHANGED
|
@@ -1,134 +1,144 @@
|
|
|
1
|
-
//
|
|
2
|
-
// · 信令(连接信息)走现成的端到端加密消息(type: 'file.rtc'),中继只转这几条小消息
|
|
3
|
-
// ·
|
|
4
|
-
// · 通行证(TURN 用户名 / 密码)一次一小时,向号码服务要(只给领过号的身份)
|
|
5
|
-
// · 一次传输开一条,传完就关;不常驻在线
|
|
6
|
-
// 通道上跑一个很小的“请求 / 回答”:
|
|
7
|
-
// 文字消息 = JSON { r: 请求号, ... };二进制消息 = [请求号 4 字节][第几片 4 字节][共几片 4 字节] + 内容(大块切成 64 KB 一片,SCTP 一条消息不能太大)
|
|
8
|
-
// 注意:node-datachannel 的通道对象要一直有人引用着,不然会被回收、通道悄悄断掉(12-03 实测)
|
|
9
|
-
const PART = 64 * 1024
|
|
10
|
-
const HIGH = 4 << 20, LOW = 1 << 20
|
|
11
|
-
|
|
12
|
-
let NDC = null, ndcErr = null
|
|
13
|
-
async function lib() {
|
|
14
|
-
if (NDC || ndcErr) return NDC
|
|
15
|
-
try { NDC = (await import('node-datachannel')).default } catch (e) { ndcErr = e }
|
|
16
|
-
return NDC
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
1
|
+
// 远程直连(12-03):两台设备不在一个局域网时,用 WebRTC 数据通道直接传文件,文件不经过服务器。
|
|
2
|
+
// · 信令(连接信息)走现成的端到端加密消息(type: 'file.rtc'),中继只转这几条小消息
|
|
3
|
+
// · 远程直连用服务器上的 STUN;打不通(两边都是对称 NAT,比如很多手机流量网络)才走服务器的 TURN 中转——服务器那边限速、限量
|
|
4
|
+
// · 通行证(TURN 用户名 / 密码)一次一小时,向号码服务要(只给领过号的身份)
|
|
5
|
+
// · 一次传输开一条,传完就关;不常驻在线
|
|
6
|
+
// 通道上跑一个很小的“请求 / 回答”:
|
|
7
|
+
// 文字消息 = JSON { r: 请求号, ... };二进制消息 = [请求号 4 字节][第几片 4 字节][共几片 4 字节] + 内容(大块切成 64 KB 一片,SCTP 一条消息不能太大)
|
|
8
|
+
// 注意:node-datachannel 的通道对象要一直有人引用着,不然会被回收、通道悄悄断掉(12-03 实测)
|
|
9
|
+
const PART = 64 * 1024
|
|
10
|
+
const HIGH = 4 << 20, LOW = 1 << 20
|
|
11
|
+
|
|
12
|
+
let NDC = null, ndcErr = null
|
|
13
|
+
async function lib() {
|
|
14
|
+
if (NDC || ndcErr) return NDC
|
|
15
|
+
try { NDC = (await import('node-datachannel')).default } catch (e) { ndcErr = e }
|
|
16
|
+
return NDC
|
|
17
|
+
}
|
|
18
|
+
/** 这台机器能不能远程直连(装没装上 node-datachannel) */
|
|
19
19
|
export async function p2pAvailable() { return !!(await lib()) }
|
|
20
20
|
/** 没装上时的原因(手机日志里要看得到真实报错,不然只能猜) */
|
|
21
|
-
export function p2pError() {
|
|
22
|
-
|
|
23
|
-
function frame(r, idx, total, body) { const h = Buffer.alloc(12); h.writeUInt32BE(r >>> 0, 0); h.writeUInt32BE(idx, 4); h.writeUInt32BE(total, 8); return Buffer.concat([h, body]) }
|
|
24
|
-
|
|
25
|
-
/** 包一条打开的数据通道:request(头, 内容?) → { head, body };onRequest((头, 内容) → { head, body }) */
|
|
26
|
-
function wrapChannel(dc, pc, log) {
|
|
27
|
-
let nextR = 1, closed = false
|
|
28
|
-
const pending = new Map(), parts = new Map(), waitingBody = new Map()
|
|
29
|
-
let handler = null, onClose = []
|
|
30
|
-
const drained = []
|
|
31
|
-
dc.setBufferedAmountLowThreshold(LOW)
|
|
32
|
-
dc.onBufferedAmountLow(() => { while (drained.length && dc.bufferedAmount() < HIGH) drained.shift()() })
|
|
33
|
-
const room = () => (dc.bufferedAmount() < HIGH ? Promise.resolve() : new Promise((ok) => drained.push(ok)))
|
|
34
|
-
async function sendBody(r, body) {
|
|
35
|
-
const total = Math.max(1, Math.ceil(body.length / PART))
|
|
36
|
-
for (let i = 0; i < total; i++) { await room(); if (closed) throw new Error('直连断了'); dc.sendMessageBinary(frame(r, i, total, body.subarray(i * PART, (i + 1) * PART))) }
|
|
37
|
-
}
|
|
38
|
-
function gotBody(r, buf) {
|
|
39
|
-
const idx = buf.readUInt32BE(4), total = buf.readUInt32BE(8), p = parts.get(r) ?? { n: 0, a: new Array(total) }
|
|
40
|
-
p.a[idx] = buf.subarray(12); p.n++; parts.set(r, p)
|
|
41
|
-
if (p.n < total) return
|
|
42
|
-
parts.delete(r); const body = Buffer.concat(p.a)
|
|
43
|
-
const w = waitingBody.get(r); if (w) { waitingBody.delete(r); w(body) }
|
|
44
|
-
}
|
|
45
|
-
const bodyOf = (r) => new Promise((ok) => waitingBody.set(r, ok))
|
|
46
|
-
dc.onMessage(async (m) => {
|
|
47
|
-
if (typeof m === 'string') {
|
|
48
|
-
let j; try { j = JSON.parse(m) } catch { return }
|
|
49
|
-
if (j.resp) { const p = pending.get(j.r); if (!p) return; pending.delete(j.r); p(j.hasBody ? { head: j, body: await bodyOf(j.r) } : { head: j, body: null }); return }
|
|
50
|
-
// 对方来的请求:有内容的先等内容到齐
|
|
51
|
-
const body = j.hasBody ? await bodyOf(j.r) : null
|
|
52
|
-
let out
|
|
53
|
-
try { out = handler ? await handler(j, body) : { head: { code: 404 } } } catch (e) { out = { head: { code: 500, error: String(e?.message ?? e) } } }
|
|
54
|
-
if (closed) return
|
|
55
|
-
dc.sendMessage(JSON.stringify({ ...out.head, r: j.r, resp: 1, hasBody: !!out.body }))
|
|
56
|
-
if (out.body) sendBody(j.r, out.body).catch(() => {})
|
|
57
|
-
return
|
|
58
|
-
}
|
|
59
|
-
const buf = Buffer.isBuffer(m) ? m : Buffer.from(m)
|
|
60
|
-
gotBody(buf.readUInt32BE(0), buf) // 通道是有序的:内容总在它的请求 / 回答后面到,那时已经登记了“等内容”
|
|
61
|
-
})
|
|
62
|
-
const shutdown = () => { if (closed) return; closed = true; for (const p of pending.values()) p({ head: { code: 499, error: '直连断了' }, body: null }); pending.clear(); drained.splice(0).forEach((f) => f()); onClose.splice(0).forEach((f) => f()) }
|
|
63
|
-
dc.onClosed(shutdown)
|
|
64
|
-
return {
|
|
65
|
-
get route() { const p = pc.getSelectedCandidatePair?.(); const t = p?.local?.type; return t === 'relay' || p?.remote?.type === 'relay' ? 'relay' : t === 'host' && p?.remote?.type === 'host' ? 'host' : 'direct' },
|
|
66
|
-
async request(head, body = null, ms = 60_000) {
|
|
67
|
-
if (closed) throw new Error('直连断了')
|
|
68
|
-
const r = nextR++
|
|
69
|
-
const res = new Promise((ok, no) => { const t = setTimeout(() => { pending.delete(r); no(new Error('直连没回话')) }, ms); pending.set(r, (x) => { clearTimeout(t); ok(x) }) })
|
|
70
|
-
dc.sendMessage(JSON.stringify({ ...head, r, hasBody: !!body }))
|
|
71
|
-
if (body) await sendBody(r, body)
|
|
72
|
-
return res
|
|
73
|
-
},
|
|
74
|
-
onRequest(fn) { handler = fn },
|
|
75
|
-
onClose(fn) { onClose.push(fn) },
|
|
76
|
-
close() { try { dc.close() } catch {} try { pc.close() } catch {} shutdown() },
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
*
|
|
82
|
-
* 发起:await open(对方公钥) → 通道;接听:onSignal(对方公钥, 消息, (通道) => {...})
|
|
83
|
-
*/
|
|
84
|
-
export function createP2PLink({ send, iceServers = async () => null, log = () => {} }) {
|
|
85
|
-
const sessions = new Map() // sid → { pc, dc, peer, resolve, reject, link }
|
|
86
|
-
const keep = new Set()
|
|
87
|
-
const PUBLIC_STUN = ['stun:stun.miwifi.com:3478', 'stun:stun.qq.com:3478']
|
|
88
|
-
async function config() {
|
|
89
|
-
let c = null; try { c = await iceServers() } catch (e) { log('[直连]
|
|
90
|
-
const enc = encodeURIComponent
|
|
91
|
-
const list = (c?.iceServers ?? []).map((u) => (u.startsWith('turn:') && c.username ? u.replace('turn:', 'turn:' + enc(c.username) + ':' + enc(c.credential) + '@') : u))
|
|
92
|
-
return { iceServers: [...list, ...PUBLIC_STUN] }
|
|
93
|
-
}
|
|
94
|
-
function wire(sid, peer, pc) {
|
|
95
|
-
pc.onLocalDescription((sdp, type) => send(peer, { type: 'file.rtc', sid, k: 'sdp', sdp, t: type }).catch?.(() => {}))
|
|
96
|
-
pc.onLocalCandidate((c, mid) => send(peer, { type: 'file.rtc', sid, k: 'cand', c, mid }).catch?.(() => {}))
|
|
97
|
-
pc.onStateChange((st) => { if (st === 'failed' || st === 'closed') { const s = sessions.get(sid); s?.reject?.(new Error('
|
|
98
|
-
}
|
|
99
|
-
function cleanup(sid) { const s = sessions.get(sid); if (!s) return; sessions.delete(sid); keep.delete(s.pc); keep.delete(s.dc) }
|
|
100
|
-
/** 发起一条直连;ms 内没打通就放弃 */
|
|
101
|
-
async function open(peer, ms = 20_000) {
|
|
102
|
-
const N = await lib(); if (!N) throw new Error('
|
|
103
|
-
const sid = Math.random().toString(36).slice(2, 12)
|
|
104
|
-
const pc = new N.PeerConnection('yu-' + sid, await config()); keep.add(pc)
|
|
105
|
-
const s = { pc, peer }; sessions.set(sid, s)
|
|
106
|
-
wire(sid, peer, pc)
|
|
107
|
-
return await new Promise((ok, no) => {
|
|
108
|
-
const t = setTimeout(() => { no(new Error('
|
|
109
|
-
s.reject = (e) => { clearTimeout(t); no(e) }
|
|
110
|
-
const dc = pc.createDataChannel('yusho-file', { ordered: true }); s.dc = dc; keep.add(dc)
|
|
111
|
-
dc.onOpen(() => { clearTimeout(t); const link = wrapChannel(dc, pc, log); link.onClose(() => cleanup(sid)); s.link = link; log('[直连] 打通了:' + link.route); ok(link) })
|
|
112
|
-
})
|
|
113
|
-
}
|
|
114
|
-
/** 收到对方的信令(file.rtc)。onLink:对方发起的通道打开时交给它 */
|
|
115
|
-
async function onSignal(peer, m, onLink) {
|
|
116
|
-
const sid = String(m.sid ?? ''); if (!/^[a-z0-9]{6,16}$/.test(sid)) return
|
|
117
|
-
let s = sessions.get(sid)
|
|
118
|
-
if (!s) {
|
|
119
|
-
if (m.k !== 'sdp' || m.t !== 'offer') return
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
s = {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
21
|
+
export function p2pError() { if (!ndcErr) return null; const m = String(ndcErr?.message ?? ndcErr); const i = m.lastIndexOf('(Error: '); return (i >= 0 ? m.slice(i + 8).replace(/\)\s*$/, '') : m).slice(0, 400) } // node-datachannel 外面那句套话很长,真正的原因在 (Error: …) 里
|
|
22
|
+
|
|
23
|
+
function frame(r, idx, total, body) { const h = Buffer.alloc(12); h.writeUInt32BE(r >>> 0, 0); h.writeUInt32BE(idx, 4); h.writeUInt32BE(total, 8); return Buffer.concat([h, body]) }
|
|
24
|
+
|
|
25
|
+
/** 包一条打开的数据通道:request(头, 内容?) → { head, body };onRequest((头, 内容) → { head, body }) */
|
|
26
|
+
function wrapChannel(dc, pc, log) {
|
|
27
|
+
let nextR = 1, closed = false
|
|
28
|
+
const pending = new Map(), parts = new Map(), waitingBody = new Map()
|
|
29
|
+
let handler = null, onClose = []
|
|
30
|
+
const drained = []
|
|
31
|
+
dc.setBufferedAmountLowThreshold(LOW)
|
|
32
|
+
dc.onBufferedAmountLow(() => { while (drained.length && dc.bufferedAmount() < HIGH) drained.shift()() })
|
|
33
|
+
const room = () => (dc.bufferedAmount() < HIGH ? Promise.resolve() : new Promise((ok) => drained.push(ok)))
|
|
34
|
+
async function sendBody(r, body) {
|
|
35
|
+
const total = Math.max(1, Math.ceil(body.length / PART))
|
|
36
|
+
for (let i = 0; i < total; i++) { await room(); if (closed) throw new Error('直连断了'); dc.sendMessageBinary(frame(r, i, total, body.subarray(i * PART, (i + 1) * PART))) }
|
|
37
|
+
}
|
|
38
|
+
function gotBody(r, buf) {
|
|
39
|
+
const idx = buf.readUInt32BE(4), total = buf.readUInt32BE(8), p = parts.get(r) ?? { n: 0, a: new Array(total) }
|
|
40
|
+
p.a[idx] = buf.subarray(12); p.n++; parts.set(r, p)
|
|
41
|
+
if (p.n < total) return
|
|
42
|
+
parts.delete(r); const body = Buffer.concat(p.a)
|
|
43
|
+
const w = waitingBody.get(r); if (w) { waitingBody.delete(r); w(body) }
|
|
44
|
+
}
|
|
45
|
+
const bodyOf = (r) => new Promise((ok) => waitingBody.set(r, ok))
|
|
46
|
+
dc.onMessage(async (m) => {
|
|
47
|
+
if (typeof m === 'string') {
|
|
48
|
+
let j; try { j = JSON.parse(m) } catch { return }
|
|
49
|
+
if (j.resp) { const p = pending.get(j.r); if (!p) return; pending.delete(j.r); p(j.hasBody ? { head: j, body: await bodyOf(j.r) } : { head: j, body: null }); return }
|
|
50
|
+
// 对方来的请求:有内容的先等内容到齐
|
|
51
|
+
const body = j.hasBody ? await bodyOf(j.r) : null
|
|
52
|
+
let out
|
|
53
|
+
try { out = handler ? await handler(j, body) : { head: { code: 404 } } } catch (e) { out = { head: { code: 500, error: String(e?.message ?? e) } } }
|
|
54
|
+
if (closed) return
|
|
55
|
+
dc.sendMessage(JSON.stringify({ ...out.head, r: j.r, resp: 1, hasBody: !!out.body }))
|
|
56
|
+
if (out.body) sendBody(j.r, out.body).catch(() => {})
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
const buf = Buffer.isBuffer(m) ? m : Buffer.from(m)
|
|
60
|
+
gotBody(buf.readUInt32BE(0), buf) // 通道是有序的:内容总在它的请求 / 回答后面到,那时已经登记了“等内容”
|
|
61
|
+
})
|
|
62
|
+
const shutdown = () => { if (closed) return; closed = true; for (const p of pending.values()) p({ head: { code: 499, error: '直连断了' }, body: null }); pending.clear(); drained.splice(0).forEach((f) => f()); onClose.splice(0).forEach((f) => f()) }
|
|
63
|
+
dc.onClosed(shutdown)
|
|
64
|
+
return {
|
|
65
|
+
get route() { const p = pc.getSelectedCandidatePair?.(); const t = p?.local?.type; return t === 'relay' || p?.remote?.type === 'relay' ? 'relay' : t === 'host' && p?.remote?.type === 'host' ? 'host' : 'direct' },
|
|
66
|
+
async request(head, body = null, ms = 60_000) {
|
|
67
|
+
if (closed) throw new Error('直连断了')
|
|
68
|
+
const r = nextR++
|
|
69
|
+
const res = new Promise((ok, no) => { const t = setTimeout(() => { pending.delete(r); no(new Error('直连没回话')) }, ms); pending.set(r, (x) => { clearTimeout(t); ok(x) }) })
|
|
70
|
+
dc.sendMessage(JSON.stringify({ ...head, r, hasBody: !!body }))
|
|
71
|
+
if (body) await sendBody(r, body)
|
|
72
|
+
return res
|
|
73
|
+
},
|
|
74
|
+
onRequest(fn) { handler = fn },
|
|
75
|
+
onClose(fn) { onClose.push(fn) },
|
|
76
|
+
close() { try { dc.close() } catch {} try { pc.close() } catch {} shutdown() },
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 远程直连。send(对方公钥, 消息) 发信令;iceServers() 返回 { iceServers: [...], username, credential }(可以为空:那就只用公共 STUN)
|
|
82
|
+
* 发起:await open(对方公钥) → 通道;接听:onSignal(对方公钥, 消息, (通道) => {...})
|
|
83
|
+
*/
|
|
84
|
+
export function createP2PLink({ send, iceServers = async () => null, log = () => {} }) {
|
|
85
|
+
const sessions = new Map() // sid → { pc, dc, peer, resolve, reject, link }
|
|
86
|
+
const keep = new Set()
|
|
87
|
+
const PUBLIC_STUN = ['stun:stun.miwifi.com:3478', 'stun:stun.qq.com:3478']
|
|
88
|
+
async function config() {
|
|
89
|
+
let c = null; try { c = await iceServers() } catch (e) { log('[直连] 没拿到远程直连通行证:', e?.message) }
|
|
90
|
+
const enc = encodeURIComponent
|
|
91
|
+
const list = (c?.iceServers ?? []).map((u) => (u.startsWith('turn:') && c.username ? u.replace('turn:', 'turn:' + enc(c.username) + ':' + enc(c.credential) + '@') : u))
|
|
92
|
+
return { iceServers: [...list, ...PUBLIC_STUN] }
|
|
93
|
+
}
|
|
94
|
+
function wire(sid, peer, pc) {
|
|
95
|
+
pc.onLocalDescription((sdp, type) => send(peer, { type: 'file.rtc', sid, k: 'sdp', sdp, t: type }).catch?.(() => {}))
|
|
96
|
+
pc.onLocalCandidate((c, mid) => send(peer, { type: 'file.rtc', sid, k: 'cand', c, mid }).catch?.(() => {}))
|
|
97
|
+
pc.onStateChange((st) => { if (st === 'failed' || st === 'closed') { const s = sessions.get(sid); s?.reject?.(new Error('远程直连没连上')); cleanup(sid) } })
|
|
98
|
+
}
|
|
99
|
+
function cleanup(sid) { const s = sessions.get(sid); if (!s) return; sessions.delete(sid); if (s.pc) keep.delete(s.pc); if (s.dc) keep.delete(s.dc) }
|
|
100
|
+
/** 发起一条直连;ms 内没打通就放弃 */
|
|
101
|
+
async function open(peer, ms = 20_000) {
|
|
102
|
+
const N = await lib(); if (!N) throw new Error('这台设备不能远程直连(缺少组件)')
|
|
103
|
+
const sid = Math.random().toString(36).slice(2, 12)
|
|
104
|
+
const pc = new N.PeerConnection('yu-' + sid, await config()); keep.add(pc)
|
|
105
|
+
const s = { pc, peer }; sessions.set(sid, s)
|
|
106
|
+
wire(sid, peer, pc)
|
|
107
|
+
return await new Promise((ok, no) => {
|
|
108
|
+
const t = setTimeout(() => { no(new Error('远程直连没连上(20 秒)')); try { pc.close() } catch {} cleanup(sid) }, ms)
|
|
109
|
+
s.reject = (e) => { clearTimeout(t); no(e) }
|
|
110
|
+
const dc = pc.createDataChannel('yusho-file', { ordered: true }); s.dc = dc; keep.add(dc)
|
|
111
|
+
dc.onOpen(() => { clearTimeout(t); const link = wrapChannel(dc, pc, log); link.onClose(() => cleanup(sid)); s.link = link; log('[直连] 打通了:' + link.route); ok(link) })
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
/** 收到对方的信令(file.rtc)。onLink:对方发起的通道打开时交给它 */
|
|
115
|
+
async function onSignal(peer, m, onLink) {
|
|
116
|
+
const sid = String(m.sid ?? ''); if (!/^[a-z0-9]{6,16}$/.test(sid)) return
|
|
117
|
+
let s = sessions.get(sid)
|
|
118
|
+
if (!s) {
|
|
119
|
+
if (m.k !== 'sdp' || m.t !== 'offer') return
|
|
120
|
+
// 先登记会话再去等组件和通行证:对方的候选地址紧跟着 offer 就到,以前这时会话还没登记,候选全被丢掉,
|
|
121
|
+
// 电脑不知道手机的中转地址,手机用流量时就连不上(12-03 实机:20 秒超时)。等的这段时间里到的信令先排队
|
|
122
|
+
s = { peer, queue: [] }; sessions.set(sid, s)
|
|
123
|
+
const N = await lib(); if (!N) { cleanup(sid); send(peer, { type: 'file.rtc', sid, k: 'nope', reason: '对方不能远程直连' }).catch?.(() => {}); return }
|
|
124
|
+
const pc = new N.PeerConnection('yu-' + sid, await config()); keep.add(pc)
|
|
125
|
+
if (sessions.get(sid) !== s) { try { pc.close() } catch {} return }
|
|
126
|
+
s.pc = pc; wire(sid, peer, pc)
|
|
127
|
+
pc.onDataChannel((dc) => { s.dc = dc; keep.add(dc); const link = wrapChannel(dc, pc, log); link.onClose(() => cleanup(sid)); s.link = link; onLink?.(link) })
|
|
128
|
+
setTimeout(() => { if (!s.link) { try { pc.close() } catch {} cleanup(sid) } }, 30_000)
|
|
129
|
+
apply(s, m); for (const q of s.queue.splice(0)) apply(s, q)
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
if (s.peer !== peer) return
|
|
133
|
+
if (!s.pc) { if (s.queue.length < 100) s.queue.push(m); return }
|
|
134
|
+
apply(s, m)
|
|
135
|
+
}
|
|
136
|
+
function apply(s, m) {
|
|
137
|
+
if (m.k === 'nope') { s.reject?.(new Error(String(m.reason ?? '对方不能远程直连'))); return }
|
|
138
|
+
try {
|
|
139
|
+
if (m.k === 'sdp') s.pc.setRemoteDescription(String(m.sdp), String(m.t))
|
|
140
|
+
else if (m.k === 'cand') s.pc.addRemoteCandidate(String(m.c), String(m.mid ?? '0'))
|
|
141
|
+
} catch (e) { log('[直连] 信令出错:', e?.message) }
|
|
142
|
+
}
|
|
143
|
+
return { open, onSignal, available: p2pAvailable }
|
|
144
|
+
}
|
|
@@ -84,7 +84,7 @@ function killTree(child) {
|
|
|
84
84
|
}
|
|
85
85
|
const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
|
|
86
86
|
|
|
87
|
-
export async function createConnector({ home = process.env.YUSHO_HOME || path.join(os.homedir(), '.yusho-connect'), name = os.hostname(), log = (...a) => console.log(new Date().toTimeString().slice(0, 8), ...a), onChange = () => {}, owner = '后台服务', sink = null /* 测试用:不经中继,消息直接交给它 */, custom = null /* 自己跑的 Agent:{ dsh: { run } },见 runCustom */, p2p = null /*
|
|
87
|
+
export async function createConnector({ home = process.env.YUSHO_HOME || path.join(os.homedir(), '.yusho-connect'), name = os.hostname(), log = (...a) => console.log(new Date().toTimeString().slice(0, 8), ...a), onChange = () => {}, owner = '后台服务', sink = null /* 测试用:不经中继,消息直接交给它 */, custom = null /* 自己跑的 Agent:{ dsh: { run } },见 runCustom */, p2p = null /* 远程直连:{ create, iceServers }(鱼Sho 内核给,见 p2plink.mjs);没有就只走局域网 */ } = {}) {
|
|
88
88
|
fs.mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
89
89
|
const F = (n) => path.join(home, n)
|
|
90
90
|
const readJ = (n, d) => { try { return JSON.parse(fs.readFileSync(F(n), 'utf8')) } catch { return d } }
|
|
@@ -124,7 +124,7 @@ export async function createConnector({ home = process.env.YUSHO_HOME || path.jo
|
|
|
124
124
|
const tasks = new Map() // task_id -> { pendingApprovals, cancel, agent, title, started }
|
|
125
125
|
// 手机 ↔ 电脑直连传文件(同一个 Wi-Fi 时):见 lanfile.mjs
|
|
126
126
|
const lan = createLanFiles({ workDir: cfg.workDir, log })
|
|
127
|
-
//
|
|
127
|
+
// 不在同一个网络时:手机发来远程直连信令(file.rtc),这边接听,通道打开后照局域网那套处理分块请求
|
|
128
128
|
let rtc = null
|
|
129
129
|
const results = new Map(readJ('results.json', []))
|
|
130
130
|
const saveResult = (id2, p) => { results.set(id2, p); writeJ('results.json', [...results].slice(-200)) }
|
|
@@ -185,7 +185,7 @@ export async function createConnector({ home = process.env.YUSHO_HOME || path.jo
|
|
|
185
185
|
fs.writeFileSync(F('device-backups/' + from + '.json'), JSON.stringify({ pk: from, label: owners().get(from), sk: m.sk, members: m.members ?? [], at: Date.now() }), { mode: 0o600 })
|
|
186
186
|
return send(from, { type: 'backup.ok', at: Date.now() })
|
|
187
187
|
}
|
|
188
|
-
if (m.type === 'file.rtc') { if (p2p?.create) { rtc ??= p2p.create({ send: (pk, o) => send(pk, o), iceServers: p2p.iceServers, log: (...a) => log(...a) }); rtc.onSignal(from, m, (link) => lan.serveLink(link)) } else send(from, { type: 'file.rtc', sid: m.sid, k: 'nope', reason: '
|
|
188
|
+
if (m.type === 'file.rtc') { if (p2p?.create) { rtc ??= p2p.create({ send: (pk, o) => send(pk, o), iceServers: p2p.iceServers, log: (...a) => log(...a) }); rtc.onSignal(from, m, (link) => lan.serveLink(link)) } else send(from, { type: 'file.rtc', sid: m.sid, k: 'nope', reason: '这台电脑的连接器不能远程直连' }); return }
|
|
189
189
|
if (m.type === 'file.offer') { try { return send(from, await lan.offer(m, (ev) => send(from, ev))) } catch (e) { return send(from, { type: 'file.failed', id: m.id, reason: e.message }) } }
|
|
190
190
|
if (m.type === 'file.request') { try { return send(from, await lan.request(m)) } catch (e) { return send(from, { type: 'file.failed', id: m.id ?? null, req: m.req ?? null, reason: e.message }) } }
|
|
191
191
|
if (m.type === 'task.create') return runTask(m, from)
|
|
@@ -37,7 +37,7 @@ export function createLanFiles({ workDir, saveDir = path.join(os.homedir(), 'Dow
|
|
|
37
37
|
return listening
|
|
38
38
|
}
|
|
39
39
|
const bad = (res, code, msg) => { res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8' }); res.end(msg) }
|
|
40
|
-
// 三种操作(查进度 / 拿一块 / 放一块):局域网 HTTP
|
|
40
|
+
// 三种操作(查进度 / 拿一块 / 放一块):局域网 HTTP 和远程直连(12-03)共用。返回 { code, json } 或 { code, buf } 或 { code, text }
|
|
41
41
|
function opStatus(x) { return { code: 200, json: { chunks: x.chunks, got: x.dir === 'in' ? [...x.got] : null, done: !!x.done } } }
|
|
42
42
|
function opGet(x, i) {
|
|
43
43
|
if (!(i >= 0 && i < x.chunks)) return { code: 400, text: 'bad chunk' }
|
|
@@ -58,7 +58,7 @@ export function createLanFiles({ workDir, saveDir = path.join(os.homedir(), 'Dow
|
|
|
58
58
|
if (x.got.size === x.chunks && !x.done) finishIn(x).catch((e) => log('收文件出错', e.message))
|
|
59
59
|
return { code: 200, json: { ok: true, got: x.got.size, chunks: x.chunks } }
|
|
60
60
|
}
|
|
61
|
-
/**
|
|
61
|
+
/** 远程直连上来的请求:{ id, t, op, i } + 内容。同一把一次性口令,不对就 404 */
|
|
62
62
|
function serveLink(link) {
|
|
63
63
|
link.onRequest(async (h, body) => {
|
|
64
64
|
const x = xfers.get(String(h.id ?? '')); if (!x || h.t !== x.token) return { head: { code: 404, error: 'not found' } }
|