dsh-mobile-plugin 0.5.52 → 0.5.54
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/README.md +12 -0
- package/dsh-mobile-credentials/lib/credentials.js +34 -2
- package/extensions/README.md +1 -2
- package/lib/client.js +32 -15
- package/lib/impl.js +5 -0
- package/lib/mobile/directory-listing.js +3 -1
- package/lib/mobile/host-bridge/endpoints.js +2 -1
- package/lib/mobile/permissions.js +1 -3
- package/lib/mobile/workspaces.js +6 -5
- package/lib/panel/index.html +10 -10
- package/lib/relay/lan-proxy.js +15 -8
- package/lib/remote/browser-notice.cjs +118 -0
- package/lib/remote/controller.cjs +230 -0
- package/lib/remote/crypto.cjs +197 -0
- package/lib/remote/host-control.cjs +59 -0
- package/lib/remote/host.cjs +226 -0
- package/lib/remote/local-headers.cjs +102 -0
- package/lib/remote/local-upstream.cjs +144 -0
- package/lib/remote/local.cjs +173 -0
- package/lib/remote/network.cjs +42 -0
- package/lib/remote/router.cjs +194 -0
- package/lib/remote/routes.cjs +84 -0
- package/lib/remote/runtime.cjs +36 -0
- package/lib/remote/shell.cjs +101 -0
- package/lib/remote/store.cjs +60 -0
- package/lib/remote/transport.cjs +184 -0
- package/lib/remote/tunnel-helper.cjs +167 -0
- package/lib/remote/tunnels.cjs +190 -0
- package/lib/routes/mobile-api.js +7 -2
- package/lib/shared/route-order.cjs +202 -0
- package/package.json +12 -6
- package/lib/mobile/perf-trace.js +0 -142
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// 显式一次性邀请授权远程电脑,并把认证后的加密流接到本机固定网页入口。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const net = require('node:net');
|
|
5
|
+
const { WebSocketServer } = require('ws');
|
|
6
|
+
const { createPairThrottle } = require('../shared/pair-throttle.js');
|
|
7
|
+
const { readJsonBody, sendJson } = require('../shared/http-util.js');
|
|
8
|
+
const c = require('./crypto.cjs');
|
|
9
|
+
|
|
10
|
+
const PAIR_PATH = '/api/mobile/v1/remote-computers/pair';
|
|
11
|
+
const TUNNEL_PATH = '/api/mobile/v1/remote-computers/tunnel';
|
|
12
|
+
const INVITE_TTL = 10 * 60 * 1000;
|
|
13
|
+
const HANDSHAKE_MS = 10_000;
|
|
14
|
+
const KEY_ID = /^[0-9a-f]{16}$/;
|
|
15
|
+
const CONTROL_OPS = new Set(['tunnels', 'tunnels.refresh']);
|
|
16
|
+
|
|
17
|
+
function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWebPort, getLaunchToken, getConnectionInfo, onControl, now = Date.now, log = () => {} }) {
|
|
18
|
+
const tickets = new Map();
|
|
19
|
+
const sessions = new Set();
|
|
20
|
+
const throttle = createPairThrottle({ now });
|
|
21
|
+
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: c.MAX_MESSAGE });
|
|
22
|
+
let closed = false;
|
|
23
|
+
const instanceId = () => String(state.instanceId || '');
|
|
24
|
+
const name = () => String(state.name || state.instanceName || 'DSH');
|
|
25
|
+
const info = async () => getConnectionInfo ? await getConnectionInfo() : undefined;
|
|
26
|
+
const routes = async () => (typeof routesOf === 'function' ? await routesOf() : []).map(({ url, channel }) => ({ url, channel }));
|
|
27
|
+
const pairAad = (ticketId, direction) => JSON.stringify(['dsh-computer-pair-v1', instanceId(), ticketId, direction]);
|
|
28
|
+
|
|
29
|
+
function valid(record) {
|
|
30
|
+
return record && record.instanceId === instanceId() && record.remoteWeb === true && !record.revokedAt && (!record.expiresAt || record.expiresAt > now());
|
|
31
|
+
}
|
|
32
|
+
function recordOf(credential, keyId, deviceId) {
|
|
33
|
+
const record = credentials.find(credential, instanceId());
|
|
34
|
+
return valid(record) && record.keyId === keyId && record.deviceId === deviceId ? record : null;
|
|
35
|
+
}
|
|
36
|
+
function stop(session, code = 4003) {
|
|
37
|
+
if (session.stopped) return;
|
|
38
|
+
session.stopped = true;
|
|
39
|
+
clearTimeout(session.timer);
|
|
40
|
+
const failure = code === 4001 ? 'REMOTE_EXPIRED' : code === 4003 ? 'REMOTE_REVOKED' : code === 4000 ? 'REMOTE_TIMEOUT' : 'REMOTE_CONNECT';
|
|
41
|
+
if (session.stream) session.stream.endAccess(failure);
|
|
42
|
+
else session.deny?.(failure);
|
|
43
|
+
session.upstream?.destroy();
|
|
44
|
+
if (session.ws.readyState < 2) session.ws.close(code);
|
|
45
|
+
const timer = setTimeout(() => session.ws.terminate(), 250);
|
|
46
|
+
timer.unref?.();
|
|
47
|
+
}
|
|
48
|
+
function checkAuthorization() {
|
|
49
|
+
for (const session of sessions) {
|
|
50
|
+
if (session.expiresAt && session.expiresAt <= now()) stop(session, 4001);
|
|
51
|
+
else if (session.credential) {
|
|
52
|
+
const record = recordOf(session.credential, session.keyId, session.deviceId);
|
|
53
|
+
if (!record || record.deviceKey !== session.deviceKey) stop(session);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const poll = setInterval(checkAuthorization, 1000);
|
|
58
|
+
poll.unref?.();
|
|
59
|
+
|
|
60
|
+
async function mintInvite() {
|
|
61
|
+
if (closed) throw c.error('REMOTE_CONNECT', 'Remote host is closed');
|
|
62
|
+
for (const [id, value] of tickets) if (value.expiresAt <= now()) tickets.delete(id);
|
|
63
|
+
const payload = { type: 'dsh-computer', version: 1, instanceId: instanceId(), name: name(), ticketId: c.random(16), ticket: c.random(), expiresAt: now() + INVITE_TTL, routes: await routes() };
|
|
64
|
+
tickets.set(payload.ticketId, payload);
|
|
65
|
+
return { invite: `dshcomputer://v1?data=${c.json(payload).toString('base64url')}`, expiresAt: payload.expiresAt };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function handlePair(req, res) {
|
|
69
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, code: 'REMOTE_METHOD' }); return; }
|
|
70
|
+
if (closed) { sendJson(res, 503, { ok: false, code: 'REMOTE_CONNECT' }); return; }
|
|
71
|
+
const rate = throttle.take();
|
|
72
|
+
if (!rate.allowed) { res.setHeader('retry-after', String(rate.retryAfterSec)); sendJson(res, 429, { ok: false, code: 'REMOTE_RATE_LIMIT' }); return; }
|
|
73
|
+
const timeout = setTimeout(() => req.destroy(), HANDSHAKE_MS);
|
|
74
|
+
timeout.unref?.();
|
|
75
|
+
let body;
|
|
76
|
+
try { body = await readJsonBody(req, c.MAX_HANDSHAKE); } finally { clearTimeout(timeout); }
|
|
77
|
+
const ticket = body && tickets.get(body.ticketId);
|
|
78
|
+
try {
|
|
79
|
+
if (!ticket || ticket.expiresAt <= now() || body.instanceId !== instanceId() || body.v !== 1) throw c.error('REMOTE_AUTH');
|
|
80
|
+
const keys = c.pairKeys(ticket.ticket, instanceId(), ticket.ticketId);
|
|
81
|
+
const request = c.openJson(keys.up, body.sealed, pairAad(ticket.ticketId, 'up'));
|
|
82
|
+
c.keyBytes(request.deviceKey);
|
|
83
|
+
c.keyBytes(request.nonce);
|
|
84
|
+
if (!KEY_ID.test(request.keyId) || typeof request.deviceId !== 'string' || !request.deviceId || request.deviceId.length > 128) throw c.error('REMOTE_AUTH');
|
|
85
|
+
// 在任何异步工作前消耗:同一邀请的并行请求只能有一份获得授权。
|
|
86
|
+
tickets.delete(ticket.ticketId);
|
|
87
|
+
const device = { deviceId: request.deviceId, name: String(request.name || 'Computer').slice(0, 128), platform: 'computer' };
|
|
88
|
+
const issued = credentials.issue(instanceId(), device, '', undefined, { deviceKey: request.deviceKey, keyId: request.keyId, permissions: [], remoteWeb: true });
|
|
89
|
+
const binding = { instanceId: instanceId(), name: name(), deviceId: issued.deviceId, credential: issued.credential, keyId: request.keyId, routes: await routes(), createdAt: now(), nonce: request.nonce, connectionInfo: await info() };
|
|
90
|
+
throttle.noteSuccess();
|
|
91
|
+
sendJson(res, 200, { ok: true, v: 1, sealed: c.sealJson(keys.down, binding, pairAad(ticket.ticketId, 'down')) });
|
|
92
|
+
} catch {
|
|
93
|
+
throttle.noteFail();
|
|
94
|
+
sendJson(res, 401, { ok: false, code: 'REMOTE_AUTH' });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function accept(ws) {
|
|
99
|
+
const session = { ws, timer: null, stopped: false, handshaking: true };
|
|
100
|
+
sessions.add(session);
|
|
101
|
+
let stage = 'hello';
|
|
102
|
+
let context;
|
|
103
|
+
let initial;
|
|
104
|
+
const finish = () => { clearTimeout(session.timer); sessions.delete(session); session.upstream?.destroy(); };
|
|
105
|
+
ws.on('close', finish);
|
|
106
|
+
ws.on('error', finish);
|
|
107
|
+
session.timer = setTimeout(() => stop(session, 4000), HANDSHAKE_MS);
|
|
108
|
+
session.timer.unref?.();
|
|
109
|
+
const receive = async (data, binary) => {
|
|
110
|
+
try {
|
|
111
|
+
const message = c.parseMessage(data, binary);
|
|
112
|
+
if (stage === 'hello') {
|
|
113
|
+
stage = 'auth';
|
|
114
|
+
if (message.type !== 'hello' || message.instanceId !== instanceId() || !KEY_ID.test(message.keyId)) throw c.error('REMOTE_AUTH');
|
|
115
|
+
const record = typeof credentials.lookupRemoteByKeyId === 'function'
|
|
116
|
+
? credentials.lookupRemoteByKeyId(instanceId(), message.keyId)
|
|
117
|
+
: credentials.findByKeyId(instanceId(), message.keyId);
|
|
118
|
+
if (!record || record.instanceId !== instanceId()) throw c.error('REMOTE_AUTH');
|
|
119
|
+
context = { instanceId: instanceId(), keyId: message.keyId, clientNonce: message.nonce, serverNonce: c.random() };
|
|
120
|
+
initial = c.connectionKeys(record.deviceKey, context);
|
|
121
|
+
Object.assign(session, { keyId: record.keyId, deviceKey: record.deviceKey, deviceId: record.deviceId });
|
|
122
|
+
session.deny = (code) => { if (ws.readyState === 1) ws.send(JSON.stringify({ v: 1, type: 'denied', sealed: c.sealJson(initial.authDown, { ok: false, code }, initial.transcript) })); };
|
|
123
|
+
ws.send(JSON.stringify({ v: 1, type: 'challenge', nonce: context.serverNonce, sealed: c.sealJson(initial.authDown, { instanceId: instanceId(), keyId: session.keyId, clientNonce: context.clientNonce }, initial.transcript) }));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (stage !== 'auth' || message.type !== 'auth') throw c.error('REMOTE_AUTH');
|
|
127
|
+
stage = 'opening';
|
|
128
|
+
const auth = c.openJson(initial.authUp, message.sealed, initial.transcript);
|
|
129
|
+
const record = recordOf(auth.credential, session.keyId, auth.deviceId);
|
|
130
|
+
if (!record || record.deviceKey !== session.deviceKey) {
|
|
131
|
+
const known = typeof credentials.lookup === 'function' ? credentials.lookup(auth.credential, instanceId()) : null;
|
|
132
|
+
const matches = known && known.keyId === session.keyId && known.deviceId === auth.deviceId && known.deviceKey === session.deviceKey;
|
|
133
|
+
if (!matches || typeof known.remoteWeb !== 'boolean') throw c.error('REMOTE_AUTH');
|
|
134
|
+
if (known.expiresAt && known.expiresAt <= now()) throw c.error('REMOTE_EXPIRED');
|
|
135
|
+
throw c.error('REMOTE_REVOKED');
|
|
136
|
+
}
|
|
137
|
+
if (!Number.isFinite(auth.leaseMs) || auth.leaseMs <= 0) throw c.error('REMOTE_EXPIRED');
|
|
138
|
+
const expiresAt = Math.min(now() + Math.min(c.HOUR, auth.leaseMs), record.expiresAt || Infinity);
|
|
139
|
+
if (expiresAt <= now()) throw c.error('REMOTE_EXPIRED');
|
|
140
|
+
Object.assign(session, { credential: auth.credential, expiresAt });
|
|
141
|
+
const keys = c.connectionKeys(session.deviceKey, { ...context, credential: auth.credential });
|
|
142
|
+
let host = { connectionInfo: await info() };
|
|
143
|
+
checkAuthorization();
|
|
144
|
+
if (session.stopped) return;
|
|
145
|
+
if (auth.control) {
|
|
146
|
+
if (!CONTROL_OPS.has(auth.control.op) || typeof onControl !== 'function') throw c.error('REMOTE_CONTROL');
|
|
147
|
+
clearTimeout(session.timer);
|
|
148
|
+
session.timer = setTimeout(() => stop(session, 4000), 20_000);
|
|
149
|
+
session.timer.unref?.();
|
|
150
|
+
try { host.controlResult = await onControl(record, auth.control); }
|
|
151
|
+
catch (err) { throw c.error(['REMOTE_REVOKED', 'REMOTE_EXPIRED'].includes(err.code) ? err.code : 'REMOTE_CONTROL'); }
|
|
152
|
+
} else if (!auth.probe) {
|
|
153
|
+
const token = await getLaunchToken();
|
|
154
|
+
const upstreamPort = Number(await getUpstreamPort());
|
|
155
|
+
const webPort = Number(getWebPort ? await getWebPort() : upstreamPort);
|
|
156
|
+
checkAuthorization();
|
|
157
|
+
if (session.stopped || ws.readyState !== 1) return;
|
|
158
|
+
if (!token || !Number.isInteger(upstreamPort) || upstreamPort < 1 || upstreamPort > 65535 || !Number.isInteger(webPort) || webPort < 1 || webPort > 65535) throw c.error('REMOTE_UNAVAILABLE');
|
|
159
|
+
host = { ...host, port: webPort, token };
|
|
160
|
+
await new Promise((resolve, reject) => {
|
|
161
|
+
session.upstream = net.connect({ host: '127.0.0.1', port: upstreamPort, allowHalfOpen: true }, resolve);
|
|
162
|
+
session.upstream.once('error', reject);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
if (session.stopped || ws.readyState !== 1) { session.upstream?.destroy(); return; }
|
|
166
|
+
checkAuthorization();
|
|
167
|
+
if (session.stopped) return;
|
|
168
|
+
clearTimeout(session.timer);
|
|
169
|
+
session.handshaking = false;
|
|
170
|
+
ws.off('message', receive);
|
|
171
|
+
ws.send(JSON.stringify({ v: 1, type: 'ready', sealed: c.sealJson(keys.authDown, { ok: true, instanceId: instanceId(), remainingMs: Math.max(0, expiresAt - now()), host }, keys.transcript) }));
|
|
172
|
+
if (auth.probe || auth.control) { ws.close(); return; }
|
|
173
|
+
stage = 'stream';
|
|
174
|
+
const armExpiry = () => {
|
|
175
|
+
clearTimeout(session.timer);
|
|
176
|
+
session.timer = setTimeout(() => stop(session, 4001), Math.max(1, session.expiresAt - now()));
|
|
177
|
+
session.timer.unref?.();
|
|
178
|
+
};
|
|
179
|
+
const stream = c.secureStream(ws, c.codecs(keys, true), { onRenew(requested) {
|
|
180
|
+
if (session.stopped) throw c.error('REMOTE_EXPIRED');
|
|
181
|
+
const current = recordOf(session.credential, session.keyId, session.deviceId);
|
|
182
|
+
if (!current || current.deviceKey !== session.deviceKey) { stop(session); throw c.error('REMOTE_REVOKED'); }
|
|
183
|
+
if (session.expiresAt <= now() || !Number.isFinite(requested) || requested <= 0) { stop(session, 4001); throw c.error('REMOTE_EXPIRED'); }
|
|
184
|
+
session.expiresAt = Math.min(now() + Math.min(requested, c.HOUR), current.expiresAt || Infinity);
|
|
185
|
+
armExpiry();
|
|
186
|
+
return Math.max(0, session.expiresAt - now());
|
|
187
|
+
} });
|
|
188
|
+
session.stream = stream;
|
|
189
|
+
stream.on('error', () => session.upstream.destroy());
|
|
190
|
+
session.upstream.on('error', () => stream.destroy());
|
|
191
|
+
stream.pipe(session.upstream).pipe(stream);
|
|
192
|
+
armExpiry();
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (context && initial && ws.readyState === 1) {
|
|
195
|
+
ws.send(JSON.stringify({ v: 1, type: 'denied', sealed: c.sealJson(initial.authDown, { ok: false, code: err.code || 'REMOTE_AUTH' }, initial.transcript) }));
|
|
196
|
+
}
|
|
197
|
+
stop(session, err.code === 'REMOTE_EXPIRED' ? 4001 : ['REMOTE_REVOKED', 'REMOTE_AUTH'].includes(err.code) ? 4003 : 1011);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
ws.on('message', receive);
|
|
201
|
+
// 中转可先完成客户端101;等A入口真正就绪再让客户端提交首次证明。
|
|
202
|
+
ws.send(JSON.stringify({ v: 1, type: 'welcome' }));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function handleUpgrade(req, socket, head) {
|
|
206
|
+
if (req.method !== 'GET') { socket.end('HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n\r\n'); return; }
|
|
207
|
+
let pending = 0;
|
|
208
|
+
for (const session of sessions) if (session.handshaking && !session.stopped) pending++;
|
|
209
|
+
if (closed || pending >= 32) { socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); return; }
|
|
210
|
+
wss.handleUpgrade(req, socket, head, accept);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
mintInvite, handlePair, handleUpgrade, checkAuthorization,
|
|
215
|
+
revoke(deviceId) { for (const session of sessions) if (session.deviceId === deviceId) stop(session); },
|
|
216
|
+
close() {
|
|
217
|
+
closed = true;
|
|
218
|
+
clearInterval(poll);
|
|
219
|
+
tickets.clear();
|
|
220
|
+
for (const session of sessions) { stop(session, 1011); session.ws.terminate(); }
|
|
221
|
+
wss.close();
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
module.exports = { createRemoteHost, PAIR_PATH, TUNNEL_PATH, INVITE_TTL };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// 本地远程网页的边界校验与双向头隔离。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
|
|
5
|
+
const CONTROL = new Set(['authorization', 'cookie', 'host', 'origin', 'referer', 'forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip']);
|
|
6
|
+
|
|
7
|
+
function sameOrigin(req, origin, bootstrap = false) {
|
|
8
|
+
if (req.headers.host !== origin.slice(7)) return false;
|
|
9
|
+
if (req.rawHeaders) {
|
|
10
|
+
const hosts = req.rawHeaders.filter((_, index) => index % 2 === 0).filter((name) => name.toLowerCase() === 'host');
|
|
11
|
+
if (hosts.length !== 1) return false;
|
|
12
|
+
}
|
|
13
|
+
if (req.headers.origin !== undefined && req.headers.origin !== origin) return false;
|
|
14
|
+
const site = req.headers['sec-fetch-site'];
|
|
15
|
+
const navigation = req.method === 'GET' && !req.headers.origin && req.headers['sec-fetch-mode'] === 'navigate' && req.headers['sec-fetch-dest'] === 'document';
|
|
16
|
+
if (site !== undefined && site !== 'same-origin' && !((bootstrap || navigation) && (site === 'none' || site === 'same-site'))) return false;
|
|
17
|
+
if (bootstrap && req.headers['sec-fetch-mode'] && req.headers['sec-fetch-mode'] !== 'navigate') return false;
|
|
18
|
+
if (!bootstrap && !navigation && req.headers.referer) {
|
|
19
|
+
try { if (new URL(req.headers.referer).origin !== origin) return false; } catch { return false; }
|
|
20
|
+
}
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function cookieOf(header, name) {
|
|
25
|
+
const pairs = String(header || '').split(';').map((part) => part.trim());
|
|
26
|
+
const values = pairs.filter((pair) => pair.startsWith(`${name}=`)).map((pair) => pair.slice(name.length + 1));
|
|
27
|
+
return values.length === 1 ? values[0] : '';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function requestPath(value) {
|
|
31
|
+
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || /[\r\n]/.test(value)) return null;
|
|
32
|
+
try { const parsed = new URL(value, 'http://remote'); return parsed.pathname + parsed.search; } catch { return null; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function upstreamHeaders(incoming, host, jar, upgrade = false) {
|
|
36
|
+
const connection = new Set(String(incoming.connection || '').toLowerCase().split(',').map((part) => part.trim()));
|
|
37
|
+
const headers = {};
|
|
38
|
+
for (const [key, value] of Object.entries(incoming)) {
|
|
39
|
+
if (value === undefined || CONTROL.has(key) || HOP.has(key) || connection.has(key) || key.startsWith('x-dsh-') || key.startsWith('sec-fetch-')) continue;
|
|
40
|
+
headers[key] = value;
|
|
41
|
+
}
|
|
42
|
+
const authority = `127.0.0.1:${host.port}`;
|
|
43
|
+
headers.host = authority;
|
|
44
|
+
if (incoming.origin) headers.origin = `http://${authority}`;
|
|
45
|
+
if (incoming.referer) {
|
|
46
|
+
try { const url = new URL(incoming.referer); headers.referer = `http://${authority}${url.pathname}${url.search}`; } catch { /* 无效引用不转发 */ }
|
|
47
|
+
}
|
|
48
|
+
const cookie = [...jar].map(([name, value]) => `${name}=${value}`).join('; ');
|
|
49
|
+
if (cookie) headers.cookie = cookie;
|
|
50
|
+
if (upgrade) { headers.connection = 'Upgrade'; headers.upgrade = incoming.upgrade || 'websocket'; }
|
|
51
|
+
return headers;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function rememberCookies(jar, raw) {
|
|
55
|
+
for (const cookie of Array.isArray(raw) ? raw : raw ? [raw] : []) {
|
|
56
|
+
const first = String(cookie).split(';')[0];
|
|
57
|
+
const at = first.indexOf('=');
|
|
58
|
+
if (at < 1) continue;
|
|
59
|
+
const name = first.slice(0, at).trim();
|
|
60
|
+
const value = first.slice(at + 1);
|
|
61
|
+
if (!value || /;\s*max-age=0(?:;|$)/i.test(cookie)) jar.delete(name);
|
|
62
|
+
else jar.set(name, value);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function responseHeaders(incoming, localOrigin, host, upgrade = false) {
|
|
67
|
+
const headers = {};
|
|
68
|
+
const connection = new Set(String(incoming.connection || '').toLowerCase().split(',').map((part) => part.trim()));
|
|
69
|
+
for (const [key, value] of Object.entries(incoming)) {
|
|
70
|
+
if (value === undefined || key === 'set-cookie' || key.startsWith('x-dsh-') || HOP.has(key) || connection.has(key)) continue;
|
|
71
|
+
headers[key] = value;
|
|
72
|
+
}
|
|
73
|
+
if (headers.location) {
|
|
74
|
+
try {
|
|
75
|
+
const value = String(headers.location);
|
|
76
|
+
const url = new URL(value, `http://127.0.0.1:${host.port}`);
|
|
77
|
+
if (url.hostname === '127.0.0.1' && Number(url.port) === Number(host.port)) {
|
|
78
|
+
url.searchParams.delete('token');
|
|
79
|
+
headers.location = `${localOrigin}${url.pathname}${url.search}${url.hash}`;
|
|
80
|
+
} else if (value.includes(host.token)) delete headers.location;
|
|
81
|
+
} catch { delete headers.location; }
|
|
82
|
+
}
|
|
83
|
+
if (upgrade) { headers.connection = 'Upgrade'; headers.upgrade = incoming.upgrade || 'websocket'; }
|
|
84
|
+
return headers;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function safeRoutes(routes) {
|
|
88
|
+
const seen = new Set();
|
|
89
|
+
return (Array.isArray(routes) ? routes : []).flatMap((route) => {
|
|
90
|
+
try {
|
|
91
|
+
const url = new URL(route.url);
|
|
92
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) return [];
|
|
93
|
+
const row = { url: url.href.replace(/\/$/, ''), channel: String(route.channel || '') };
|
|
94
|
+
const key = `${row.channel}|${row.url}`;
|
|
95
|
+
if (!row.channel || seen.has(key)) return [];
|
|
96
|
+
seen.add(key);
|
|
97
|
+
return [row];
|
|
98
|
+
} catch { return []; }
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = { sameOrigin, cookieOf, requestPath, upstreamHeaders, rememberCookies, responseHeaders, safeRoutes };
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// 每次 HTTP 或 WebSocket 连接使用独立加密流,宿主会话只存内存。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const http = require('node:http');
|
|
5
|
+
const { upstreamHeaders, responseHeaders, rememberCookies } = require('./local-headers.cjs');
|
|
6
|
+
|
|
7
|
+
function createUpstream({ connect, active, live, origin, expiresAt, noticeTransform, onError = () => {} }) {
|
|
8
|
+
const jar = new Map();
|
|
9
|
+
let identity = '';
|
|
10
|
+
let authenticating = null;
|
|
11
|
+
|
|
12
|
+
async function connection() {
|
|
13
|
+
if (!active()) throw Object.assign(new Error('访问已结束'), { code: 'REMOTE_EXPIRED' });
|
|
14
|
+
const before = expiresAt?.();
|
|
15
|
+
const result = await connect();
|
|
16
|
+
const host = result?.host;
|
|
17
|
+
if (!result?.stream || !Number.isInteger(host?.port) || host.port < 1 || host.port > 65535 || typeof host.token !== 'string' || !host.token) {
|
|
18
|
+
result?.stream?.destroy();
|
|
19
|
+
throw new Error('远程网页握手无效');
|
|
20
|
+
}
|
|
21
|
+
if (!active()) { result.stream.destroy(); throw Object.assign(new Error('访问已结束'), { code: 'REMOTE_EXPIRED' }); }
|
|
22
|
+
live.add(result.stream);
|
|
23
|
+
result.stream.once('close', () => live.delete(result.stream));
|
|
24
|
+
result.stream.on('error', () => {});
|
|
25
|
+
if (expiresAt && before !== expiresAt() && typeof result.stream.renew === 'function') {
|
|
26
|
+
await result.stream.renew(expiresAt());
|
|
27
|
+
if (!active()) { result.stream.destroy(); throw Object.assign(new Error('访问已结束'), { code: 'REMOTE_EXPIRED' }); }
|
|
28
|
+
}
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function request({ stream, host }, options, receive) {
|
|
33
|
+
const agent = new http.Agent({ keepAlive: false });
|
|
34
|
+
agent.createConnection = (_options, callback) => { callback(null, stream); return stream; };
|
|
35
|
+
const req = http.request({ hostname: '127.0.0.1', port: host.port, ...options, agent }, receive);
|
|
36
|
+
req.once('close', () => agent.destroy());
|
|
37
|
+
return req;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function cookies(host) {
|
|
41
|
+
const key = `${host.port}:${host.token}`;
|
|
42
|
+
if (identity === key && jar.size) return;
|
|
43
|
+
if (authenticating) { await authenticating; if (identity === key && jar.size) return; }
|
|
44
|
+
authenticating = (async () => {
|
|
45
|
+
jar.clear();
|
|
46
|
+
const upstream = await connection();
|
|
47
|
+
if (upstream.host.port !== host.port || upstream.host.token !== host.token) { upstream.stream.destroy(); throw new Error('远程网页会话已改变'); }
|
|
48
|
+
await new Promise((resolve, reject) => {
|
|
49
|
+
const req = request(upstream, {
|
|
50
|
+
method: 'GET', path: `/?token=${encodeURIComponent(host.token)}`,
|
|
51
|
+
headers: { host: `127.0.0.1:${host.port}`, accept: 'text/html', connection: 'close' },
|
|
52
|
+
}, (res) => {
|
|
53
|
+
rememberCookies(jar, res.headers['set-cookie']);
|
|
54
|
+
res.resume();
|
|
55
|
+
if (res.statusCode >= 400 || !jar.size) reject(new Error('远程网页认证失败'));
|
|
56
|
+
else { identity = key; resolve(); }
|
|
57
|
+
});
|
|
58
|
+
const timer = setTimeout(() => req.destroy(new Error('远程网页认证超时')), 8000);
|
|
59
|
+
timer.unref?.();
|
|
60
|
+
req.once('close', () => clearTimeout(timer));
|
|
61
|
+
req.once('error', reject);
|
|
62
|
+
req.end();
|
|
63
|
+
});
|
|
64
|
+
})();
|
|
65
|
+
try { await authenticating; } finally { authenticating = null; }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function forward(req, res) {
|
|
69
|
+
let conn;
|
|
70
|
+
let up;
|
|
71
|
+
try {
|
|
72
|
+
conn = await connection();
|
|
73
|
+
await cookies(conn.host);
|
|
74
|
+
if (res.destroyed || !active()) { conn.stream.destroy(); return; }
|
|
75
|
+
const outgoing = upstreamHeaders(req.headers, conn.host, jar);
|
|
76
|
+
outgoing['accept-encoding'] = 'identity';
|
|
77
|
+
up = request(conn, {
|
|
78
|
+
method: req.method, path: req.url, headers: outgoing,
|
|
79
|
+
}, (remote) => {
|
|
80
|
+
rememberCookies(jar, remote.headers['set-cookie']);
|
|
81
|
+
if (remote.statusCode === 401) { jar.clear(); identity = ''; }
|
|
82
|
+
const output = responseHeaders(remote.headers, origin(), conn.host);
|
|
83
|
+
const main = req.method === 'GET' && (req.headers['sec-fetch-dest'] === 'document' || (!req.headers['sec-fetch-dest'] && String(req.headers.accept || '').includes('text/html')));
|
|
84
|
+
const html = String(remote.headers['content-type'] || '').toLowerCase().startsWith('text/html');
|
|
85
|
+
const identity = !remote.headers['content-encoding'] || remote.headers['content-encoding'] === 'identity';
|
|
86
|
+
const notice = noticeTransform && main && html && identity ? noticeTransform() : null;
|
|
87
|
+
if (notice) { delete output['content-length']; delete output.etag; }
|
|
88
|
+
output['referrer-policy'] = 'no-referrer';
|
|
89
|
+
output['x-frame-options'] = 'SAMEORIGIN';
|
|
90
|
+
res.writeHead(remote.statusCode, output);
|
|
91
|
+
res.flushHeaders?.();
|
|
92
|
+
remote.on('error', () => res.destroy());
|
|
93
|
+
if (notice) { notice.on('error', () => res.destroy()); remote.pipe(notice).pipe(res); }
|
|
94
|
+
else remote.pipe(res);
|
|
95
|
+
});
|
|
96
|
+
up.once('error', (error) => fail(error));
|
|
97
|
+
req.once('aborted', () => up.destroy());
|
|
98
|
+
res.once('close', () => { if (!res.writableEnded) up.destroy(); });
|
|
99
|
+
req.pipe(up);
|
|
100
|
+
} catch (error) { conn?.stream.destroy(); fail(error); }
|
|
101
|
+
function fail(error) {
|
|
102
|
+
onError(error);
|
|
103
|
+
if (res.destroyed) return;
|
|
104
|
+
if (res.headersSent) { res.destroy(); return; }
|
|
105
|
+
res.writeHead(error.code === 'REMOTE_EXPIRED' ? 410 : 502, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
106
|
+
res.end(error.code === 'REMOTE_EXPIRED' ? '本次访问已到期,请在本机面板重新打开。' : '远程连接暂时不可用。');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function upgrade(req, socket, head) {
|
|
111
|
+
let conn;
|
|
112
|
+
try {
|
|
113
|
+
conn = await connection();
|
|
114
|
+
await cookies(conn.host);
|
|
115
|
+
if (socket.destroyed || !active()) { conn.stream.destroy(); return; }
|
|
116
|
+
const up = request(conn, { method: req.method, path: req.url, headers: upstreamHeaders(req.headers, conn.host, jar, true) });
|
|
117
|
+
const drop = () => { socket.destroy(); conn.stream.destroy(); };
|
|
118
|
+
up.once('error', (error) => { onError(error); drop(); });
|
|
119
|
+
up.once('response', (remote) => { remote.resume(); drop(); });
|
|
120
|
+
up.once('upgrade', (remote, stream, upstreamHead) => {
|
|
121
|
+
rememberCookies(jar, remote.headers['set-cookie']);
|
|
122
|
+
const headers = responseHeaders(remote.headers, origin(), conn.host, true);
|
|
123
|
+
const lines = [`HTTP/1.1 ${remote.statusCode} ${remote.statusMessage || 'Switching Protocols'}`];
|
|
124
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
125
|
+
for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
|
|
126
|
+
}
|
|
127
|
+
socket.write(`${lines.join('\r\n')}\r\n\r\n`, 'latin1');
|
|
128
|
+
if (upstreamHead.length) socket.write(upstreamHead);
|
|
129
|
+
if (head.length) stream.write(head);
|
|
130
|
+
stream.on('error', drop);
|
|
131
|
+
socket.on('error', drop);
|
|
132
|
+
socket.once('close', () => stream.destroy());
|
|
133
|
+
stream.once('close', () => socket.destroy());
|
|
134
|
+
socket.pipe(stream); stream.pipe(socket);
|
|
135
|
+
});
|
|
136
|
+
socket.once('close', () => up.destroy());
|
|
137
|
+
up.end();
|
|
138
|
+
} catch (error) { onError(error); conn?.stream.destroy(); socket.destroy(); }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { forward, upgrade, close() { jar.clear(); identity = ''; } };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
module.exports = { createUpstream };
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// 只监听本机的远程网页入口:一次性打开链接、访问租期与按窗口自动续期。
|
|
2
|
+
// 每台网关各管各的租期;续期只延长期限,不重发入口地址、不动已建立的连接。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const http = require('node:http');
|
|
6
|
+
const crypto = require('node:crypto');
|
|
7
|
+
const { sameOrigin, cookieOf, requestPath } = require('./local-headers.cjs');
|
|
8
|
+
const { createUpstream } = require('./local-upstream.cjs');
|
|
9
|
+
const { noticeScript, createNoticeTransform } = require('./browser-notice.cjs');
|
|
10
|
+
|
|
11
|
+
const LEASE_MS = 60 * 60 * 1000;
|
|
12
|
+
const OPEN_MS = 60 * 1000;
|
|
13
|
+
const ACTIVE_MS = 5 * 60 * 1000;
|
|
14
|
+
const RENEW_AHEAD_MS = 5 * 60 * 1000;
|
|
15
|
+
const RENEW_CHECK_MS = 30 * 1000;
|
|
16
|
+
// 判定「桌面窗口还连着」的宽限:刚有过请求也算连着,避免页面加载空档被误判成已关闭。
|
|
17
|
+
const ATTACH_GRACE_MS = 4 * 1000;
|
|
18
|
+
const OPEN_PATH = '/__dsh_remote_open';
|
|
19
|
+
|
|
20
|
+
function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError, onRenew = () => {} }) {
|
|
21
|
+
const live = new Set();
|
|
22
|
+
const cookieName = `dsh_remote_${crypto.randomBytes(12).toString('hex')}`;
|
|
23
|
+
const session = crypto.randomBytes(32).toString('base64url');
|
|
24
|
+
let ticket = crypto.randomBytes(32).toString('base64url');
|
|
25
|
+
let ticketExpiresAt = now() + OPEN_MS;
|
|
26
|
+
let deadline = Math.min(Number(expiresAt) || now() + LEASE_MS, now() + LEASE_MS);
|
|
27
|
+
let lastActivity = now();
|
|
28
|
+
let port = 0;
|
|
29
|
+
let closed = false;
|
|
30
|
+
let timer = null;
|
|
31
|
+
let renewing = false;
|
|
32
|
+
let starting = null;
|
|
33
|
+
const origin = () => `http://127.0.0.1:${port}`;
|
|
34
|
+
const active = () => !closed && now() < deadline;
|
|
35
|
+
const inUse = (time = now()) => !closed && (live.size > 0 || time - lastActivity < ACTIVE_MS);
|
|
36
|
+
const upstream = createUpstream({ connect, active, live, origin, expiresAt: () => deadline, onError, noticeTransform: createNoticeTransform });
|
|
37
|
+
const server = http.createServer(handle);
|
|
38
|
+
server.requestTimeout = 0;
|
|
39
|
+
server.headersTimeout = 15000;
|
|
40
|
+
server.on('connection', (socket) => {
|
|
41
|
+
live.add(socket);
|
|
42
|
+
lastActivity = now();
|
|
43
|
+
socket.once('close', () => live.delete(socket));
|
|
44
|
+
socket.on('error', () => {});
|
|
45
|
+
});
|
|
46
|
+
server.on('upgrade', (req, socket, head) => {
|
|
47
|
+
const path = requestPath(req.url);
|
|
48
|
+
if (!active() || !path || !sameOrigin(req, origin()) || cookieOf(req.headers.cookie, cookieName) !== session) {
|
|
49
|
+
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return;
|
|
50
|
+
}
|
|
51
|
+
lastActivity = now();
|
|
52
|
+
req.url = path;
|
|
53
|
+
void upstream.upgrade(req, socket, head);
|
|
54
|
+
});
|
|
55
|
+
server.on('clientError', (_error, socket) => socket.destroy());
|
|
56
|
+
|
|
57
|
+
function reply(res, status, text) {
|
|
58
|
+
res.writeHead(status, {
|
|
59
|
+
'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store',
|
|
60
|
+
'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff',
|
|
61
|
+
});
|
|
62
|
+
res.end(text);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function handle(req, res) {
|
|
66
|
+
const path = requestPath(req.url);
|
|
67
|
+
if (!path || !active()) return reply(res, 410, '本次访问已到期,请在本机面板重新打开。');
|
|
68
|
+
const url = new URL(path, origin());
|
|
69
|
+
const bootstrap = url.pathname === OPEN_PATH;
|
|
70
|
+
if (!sameOrigin(req, origin(), bootstrap)) return reply(res, 403, '只允许从本机入口访问。');
|
|
71
|
+
if (bootstrap) {
|
|
72
|
+
const value = url.searchParams.get('ticket');
|
|
73
|
+
if (req.method !== 'GET' || !ticket || now() >= ticketExpiresAt || value !== ticket) return reply(res, 403, '打开链接已失效,请在本机面板重新打开。');
|
|
74
|
+
ticket = '';
|
|
75
|
+
res.writeHead(303, {
|
|
76
|
+
location: '/', 'set-cookie': `${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict`,
|
|
77
|
+
'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
|
|
78
|
+
});
|
|
79
|
+
res.end(); return;
|
|
80
|
+
}
|
|
81
|
+
if (cookieOf(req.headers.cookie, cookieName) !== session) return reply(res, 401, '请从本机面板打开这台电脑。');
|
|
82
|
+
lastActivity = now();
|
|
83
|
+
if (url.pathname === '/__dsh_remote_status' || url.pathname === '/__dsh_remote_notice.js') {
|
|
84
|
+
if (req.method !== 'GET') return reply(res, 405, '只读入口。');
|
|
85
|
+
const status = url.pathname === '/__dsh_remote_status';
|
|
86
|
+
res.writeHead(200, { 'content-type': status ? 'application/json; charset=utf-8' : 'application/javascript; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
87
|
+
res.end(status ? JSON.stringify({ expiresAt: deadline, serverNow: now() }) : noticeScript()); return;
|
|
88
|
+
}
|
|
89
|
+
req.url = path;
|
|
90
|
+
void upstream.forward(req, res);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function arm() {
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
const remaining = Math.max(1, deadline - now());
|
|
96
|
+
timer = setTimeout(checkExpiry, Math.min(remaining, RENEW_CHECK_MS));
|
|
97
|
+
timer.unref?.();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function close() {
|
|
101
|
+
if (closed) return;
|
|
102
|
+
closed = true;
|
|
103
|
+
ticket = '';
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
upstream.close();
|
|
106
|
+
for (const stream of live) stream.destroy();
|
|
107
|
+
live.clear();
|
|
108
|
+
if (server.listening) server.close();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function checkExpiry() {
|
|
112
|
+
if (closed) return false;
|
|
113
|
+
if (now() >= deadline) { close(); onExpire(); return true; }
|
|
114
|
+
void autoRenew(now());
|
|
115
|
+
arm(); return false;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 临期且窗口还在用就原地续:只推期限,不重发入口、不动已建立的连接,页面不会刷新。 */
|
|
119
|
+
async function autoRenew(time = now()) {
|
|
120
|
+
if (closed || renewing || !active() || deadline - time > RENEW_AHEAD_MS || !inUse(time)) return false;
|
|
121
|
+
renewing = true;
|
|
122
|
+
try { await renew(); onRenew(deadline); return true; }
|
|
123
|
+
catch { return false; }
|
|
124
|
+
finally { renewing = false; }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function renew(value = now() + LEASE_MS) {
|
|
128
|
+
if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
|
|
129
|
+
let next = Math.min(Number(value) || now() + LEASE_MS, now() + LEASE_MS);
|
|
130
|
+
const streams = [...live].filter((stream) => typeof stream.renew === 'function' && !stream.destroyed);
|
|
131
|
+
const accepted = await Promise.all(streams.map((stream) => stream.renew(next)));
|
|
132
|
+
const added = [...live].filter((stream) => !streams.includes(stream) && typeof stream.renew === 'function' && !stream.destroyed);
|
|
133
|
+
accepted.push(...await Promise.all(added.map((stream) => stream.renew(next))));
|
|
134
|
+
if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
|
|
135
|
+
for (const result of accepted) if (Number.isFinite(result)) next = Math.min(next, result);
|
|
136
|
+
deadline = next;
|
|
137
|
+
arm(); return { expiresAt: deadline };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
start() {
|
|
142
|
+
if (starting) return starting;
|
|
143
|
+
starting = new Promise((resolve, reject) => {
|
|
144
|
+
server.once('error', reject);
|
|
145
|
+
server.listen(0, '127.0.0.1', () => {
|
|
146
|
+
server.removeListener('error', reject);
|
|
147
|
+
if (closed) { server.close(); reject(Object.assign(new Error('访问已停止'), { code: 'REMOTE_CONNECT' })); return; }
|
|
148
|
+
server.on('error', () => close());
|
|
149
|
+
port = server.address().port;
|
|
150
|
+
server.unref?.(); arm();
|
|
151
|
+
resolve({ url: `${origin()}${OPEN_PATH}?ticket=${ticket}`, expiresAt: deadline });
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
return starting;
|
|
155
|
+
},
|
|
156
|
+
openLink() {
|
|
157
|
+
if (!active()) throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' });
|
|
158
|
+
ticket = crypto.randomBytes(32).toString('base64url');
|
|
159
|
+
ticketExpiresAt = now() + OPEN_MS;
|
|
160
|
+
return { url: `${origin()}${OPEN_PATH}?ticket=${ticket}`, expiresAt: deadline };
|
|
161
|
+
},
|
|
162
|
+
renew,
|
|
163
|
+
expiresAt: () => deadline,
|
|
164
|
+
/** 桌面窗口此刻是否连着:有活连接,或刚有过请求(关闭判定给 4 秒宽限,避免加载空档误报)。 */
|
|
165
|
+
attached() { return !closed && (live.size > 0 || now() - lastActivity < ATTACH_GRACE_MS); },
|
|
166
|
+
inUse,
|
|
167
|
+
autoRenew,
|
|
168
|
+
disconnect() { for (const stream of live) stream.destroy(); live.clear(); upstream.close(); },
|
|
169
|
+
checkExpiry, close,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = { createLocalGateway, LEASE_MS, OPEN_MS };
|