@tianacloud/dsh-remote 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,375 @@
1
+ import { base64UrlDecode, concatBytes, MSG_E2EE_BOX, MSG_E2EE_CTRL } from './e2ee.js';
2
+
3
+ const WINDOW = 128;
4
+ const WINDOW_BYTES = 2 << 20;
5
+ const MAX_QUEUE_BYTES = 8 << 20;
6
+ const MAX_QUEUE_FRAMES = 256;
7
+ export const CHUNK_SIZE = 32 << 10;
8
+ export const RELAY_GRACE_MS = 30_000;
9
+ export const LEASE_MS = 2 * 60 * 60 * 1000;
10
+ export const RENEW_MS = 110 * 60 * 1000;
11
+ const MAX_BOX = CHUNK_SIZE + 30;
12
+ const MAX_CONTROL = 66 << 10;
13
+ const CONTROL_MASK = (1n << 64n) - 1n;
14
+ const encode = new TextEncoder();
15
+ const decode = new TextDecoder();
16
+
17
+ function seqOf(bytes) {
18
+ return new DataView(bytes.buffer, bytes.byteOffset, 8).getBigUint64(0);
19
+ }
20
+
21
+ export function sessionPrefix(id) {
22
+ return base64UrlDecode(id);
23
+ }
24
+
25
+ export class MultipathSession {
26
+ constructor({ cipher, onData, onControl, onClose, onStall, leaseMs = LEASE_MS, initialLeaseMs }) {
27
+ this.cipher = cipher;
28
+ this.prefix = sessionPrefix(cipher.logicalSessionId);
29
+ this.onData = onData;
30
+ this.onControl = onControl;
31
+ this.onClose = onClose;
32
+ this.onStall = onStall;
33
+ this.leaseMs = Math.min(leaseMs, LEASE_MS);
34
+ this.unacked = new Map();
35
+ this.unackedBytes = 0;
36
+ this.queue = [];
37
+ this.queueBytes = 0;
38
+ this.received = new Map();
39
+ this.verifying = new Set();
40
+ this.controlVerifying = new Set();
41
+ this.controlHigh = 0n;
42
+ this.controlBits = 0n;
43
+ this.controlTail = Promise.resolve();
44
+ this.controlPending = 0;
45
+ this.delivered = 0n;
46
+ this.acknowledged = 0n;
47
+ this.lastAck = 0n;
48
+ this.closed = false;
49
+ this.lastProgress = Date.now();
50
+ this.lastRetransmit = this.lastProgress;
51
+ this.renewLease(initialLeaseMs ?? this.leaseMs);
52
+ this.ackWatcher = setInterval(() => {
53
+ if (!this.unacked.size || Date.now() - this.lastProgress < 500) return;
54
+ this.lastProgress = Date.now();
55
+ if (this.lastProgress - this.lastRetransmit >= 1000) {
56
+ this.lastRetransmit = this.lastProgress;
57
+ for (const packet of this.unacked.values()) packet.sent = false;
58
+ this.schedule();
59
+ }
60
+ if (++this.stalls >= 6) {
61
+ this.stalls = 0;
62
+ this.onStall?.(this.primary);
63
+ }
64
+ void this.control({ type: 'ack_req' }).catch(() => {});
65
+ }, 250);
66
+ this.stalls = 0;
67
+ }
68
+
69
+ renewLease(durationMs = this.leaseMs) {
70
+ if (this.closed) return;
71
+ clearTimeout(this.lease);
72
+ const granted = Math.max(1, Math.min(this.leaseMs, Number.isFinite(durationMs) ? Math.floor(durationMs) : this.leaseMs));
73
+ this.expiresAt = Date.now() + granted;
74
+ this.lease = setTimeout(() => this.close(new Error('授权租期已到期')), granted);
75
+ }
76
+
77
+ live() {
78
+ if (this.closed) return false;
79
+ if (Date.now() < this.expiresAt) return true;
80
+ this.close(new Error('授权租期已到期'));
81
+ return false;
82
+ }
83
+
84
+ setRelay(path, reschedule = true) {
85
+ this.relay = path;
86
+ if (reschedule) this.selectPath();
87
+ }
88
+
89
+ setP2P(path) {
90
+ this.p2p = path;
91
+ this.selectPath();
92
+ }
93
+
94
+ selectPath() {
95
+ const path = this.p2p?.ready() ? this.p2p : this.relay?.ready() ? this.relay : null;
96
+ if (this.primary !== path) {
97
+ this.primary = path;
98
+ for (const packet of this.unacked.values()) packet.sent = false;
99
+ this.lastProgress = Date.now();
100
+ this.stalls = 0;
101
+ }
102
+ this.schedule();
103
+ }
104
+
105
+ schedule(delay = 0) {
106
+ if (this.closed || this.pumping || this.scheduled) return;
107
+ this.scheduled = setTimeout(() => {
108
+ this.scheduled = null;
109
+ void this.pump().catch((err) => this.close(err));
110
+ }, delay);
111
+ }
112
+
113
+ send(body, signal) {
114
+ if (!this.live() || this.queue.length >= MAX_QUEUE_FRAMES || this.queueBytes + body.length > MAX_QUEUE_BYTES ||
115
+ body.length > MAX_BOX - 24) {
116
+ return Promise.reject(new Error('远程发送队列已关闭或超过上限'));
117
+ }
118
+ if (signal?.aborted) return Promise.reject(signal.reason);
119
+ return new Promise((resolve, reject) => {
120
+ const item = { body, resolve, reject, signal };
121
+ item.abort = () => {
122
+ const index = this.queue.indexOf(item);
123
+ if (index === -1) return;
124
+ this.queue.splice(index, 1);
125
+ this.queueBytes -= body.length;
126
+ reject(signal.reason);
127
+ };
128
+ signal?.addEventListener('abort', item.abort, { once: true });
129
+ this.queue.push(item);
130
+ this.queueBytes += body.length;
131
+ this.schedule();
132
+ });
133
+ }
134
+
135
+ async pump() {
136
+ if (this.pumping || !this.live()) return;
137
+ this.pumping = true;
138
+ let retry = false;
139
+ try {
140
+ while (!this.closed) {
141
+ const path = this.primary;
142
+ if (!path?.ready()) break;
143
+ if (this.controlPending || path.bufferedAmount() > path.highWater) {
144
+ retry = true;
145
+ break;
146
+ }
147
+ let packet = [...this.unacked.values()].find((entry) => !entry.sent);
148
+ if (!packet) {
149
+ const item = this.queue[0];
150
+ if (!item || this.unacked.size >= WINDOW ||
151
+ this.unackedBytes + item.body.length + 24 > WINDOW_BYTES) break;
152
+ this.queue.shift();
153
+ this.queueBytes -= item.body.length;
154
+ item.signal?.removeEventListener('abort', item.abort);
155
+ let bytes;
156
+ try {
157
+ bytes = await this.cipher.seal(item.body);
158
+ } catch (err) {
159
+ item.reject(err);
160
+ throw err;
161
+ }
162
+ if (this.closed) {
163
+ item.reject(new Error('远程连接已结束,操作结果未知'));
164
+ break;
165
+ }
166
+ packet = { bytes, sent: false };
167
+ this.unacked.set(seqOf(bytes), packet);
168
+ this.unackedBytes += bytes.length;
169
+ item.resolve(true);
170
+ }
171
+ if (path !== this.primary || !path.ready()) continue;
172
+ if (this.controlPending) {
173
+ retry = true;
174
+ break;
175
+ }
176
+ try {
177
+ if (path.send(MSG_E2EE_BOX, packet.bytes) === false) {
178
+ retry = true;
179
+ break;
180
+ }
181
+ packet.sent = true;
182
+ } catch {
183
+ path.close();
184
+ break;
185
+ }
186
+ }
187
+ } finally {
188
+ this.pumping = false;
189
+ if (retry) this.schedule(10);
190
+ }
191
+ }
192
+
193
+ control(message, path = this.primary) {
194
+ if (!this.live() || !path?.ready()) return Promise.resolve(false);
195
+ if (this.controlPending >= 64) return Promise.reject(new Error('远程控制队列超过上限'));
196
+ const bytes = encode.encode(JSON.stringify(message));
197
+ if (bytes.length > MAX_CONTROL - 40) return Promise.reject(new Error('远程控制消息超过上限'));
198
+ this.controlPending++;
199
+ const send = this.controlTail.then(async () => {
200
+ if (this.closed || !path.ready()) return false;
201
+ if (path.bufferedAmount() > path.highWater + MAX_CONTROL) return false;
202
+ const box = await this.cipher.control.seal(bytes);
203
+ if (this.closed || !path.ready()) return false;
204
+ try {
205
+ return path.send(MSG_E2EE_CTRL, concatBytes(this.prefix, box)) !== false;
206
+ } catch {
207
+ path.close();
208
+ return false;
209
+ }
210
+ }).finally(() => {
211
+ this.controlPending--;
212
+ this.schedule();
213
+ });
214
+ this.controlTail = send.catch((err) => this.close(err));
215
+ return send;
216
+ }
217
+
218
+ sendAck(path = this.primary) {
219
+ clearTimeout(this.ackTimer);
220
+ this.ackTimer = null;
221
+ const delivered = this.delivered;
222
+ void this.control({ type: 'ack', seq: String(delivered) }, path).then((sent) => {
223
+ if (sent && delivered > this.lastAck) this.lastAck = delivered;
224
+ }).catch(() => {});
225
+ }
226
+
227
+ receive(kind, packet, path) {
228
+ if (!this.live() || !path.accept(packet.length)) return;
229
+ if (kind === MSG_E2EE_CTRL) {
230
+ void this.receiveControl(packet, path).catch(() => path.invalid());
231
+ } else if (kind === MSG_E2EE_BOX && (path === this.relay || path === this.p2p)) {
232
+ void this.receiveData(packet, path).catch(() => path.invalid());
233
+ }
234
+ }
235
+
236
+ async receiveControl(packet, path) {
237
+ if (packet.length < 40 || packet.length > MAX_CONTROL ||
238
+ this.prefix.some((byte, i) => packet[i] !== byte)) return;
239
+ const box = packet.subarray(16);
240
+ const nonce = seqOf(box);
241
+ const replayed = () => nonce === 0n || this.controlHigh >= nonce + 64n ||
242
+ (nonce <= this.controlHigh && Boolean(this.controlBits & (1n << (this.controlHigh - nonce))));
243
+ if (replayed() || this.controlVerifying.has(nonce) || this.controlVerifying.size >= 64) return;
244
+ this.controlVerifying.add(nonce);
245
+ try {
246
+ const bytes = await this.cipher.control.openPacket(box);
247
+ if (this.closed || replayed() || !path.ready()) return;
248
+ if (nonce > this.controlHigh) {
249
+ const step = nonce - this.controlHigh;
250
+ this.controlBits = step >= 64n ? 1n : ((this.controlBits << step) | 1n) & CONTROL_MASK;
251
+ this.controlHigh = nonce;
252
+ } else {
253
+ this.controlBits |= 1n << (this.controlHigh - nonce);
254
+ }
255
+ const message = JSON.parse(decode.decode(bytes));
256
+ if (path !== this.relay && path !== this.p2p && !['bind_relay_leg', 'bound_relay_leg', 'lease_renew', 'path_probe', 'path_probe_ack'].includes(message.type)) return;
257
+ if (message.type === 'ack') {
258
+ if (!/^[0-9]{1,20}$/u.test(message.seq)) return;
259
+ const ack = BigInt(message.seq);
260
+ if (ack < this.acknowledged || ack > this.cipher.txSeq) return;
261
+ if (ack === this.acknowledged) return;
262
+ this.stalls = 0;
263
+ this.acknowledged = ack;
264
+ this.lastProgress = Date.now();
265
+ this.lastRetransmit = this.lastProgress;
266
+ for (const [seq, entry] of this.unacked) {
267
+ if (seq > ack) break;
268
+ this.unacked.delete(seq);
269
+ this.unackedBytes -= entry.bytes.length;
270
+ }
271
+ this.schedule();
272
+ } else if (message.type === 'ack_req') {
273
+ this.sendAck(path);
274
+ } else {
275
+ await this.onControl?.(message, path);
276
+ }
277
+ } finally {
278
+ this.controlVerifying.delete(nonce);
279
+ }
280
+ }
281
+
282
+ async receiveData(packet, path) {
283
+ if (packet.length < 29 || packet.length > MAX_BOX) return;
284
+ const seq = seqOf(packet);
285
+ if (seq <= this.delivered || seq > this.delivered + BigInt(WINDOW) ||
286
+ this.received.has(seq) || this.verifying.has(seq)) return;
287
+ this.verifying.add(seq);
288
+ try {
289
+ const plaintext = await this.cipher.openPacket(packet);
290
+ if (this.closed) return;
291
+ this.received.set(seq, plaintext);
292
+ await this.deliver();
293
+
294
+ } finally {
295
+ this.verifying.delete(seq);
296
+ }
297
+ }
298
+
299
+ async deliver() {
300
+ if (this.delivering) return;
301
+ this.delivering = true;
302
+ try {
303
+ while (!this.closed && this.received.has(this.delivered + 1n)) {
304
+ const next = this.delivered + 1n;
305
+ await this.onData(this.received.get(next));
306
+ if (this.closed) return;
307
+ this.received.delete(next);
308
+ this.delivered = next;
309
+ }
310
+ if (this.delivered - this.lastAck >= 16n) this.sendAck();
311
+ else if (this.delivered > this.lastAck && !this.ackTimer) {
312
+ this.ackTimer = setTimeout(() => this.sendAck(), 20);
313
+ }
314
+ } catch (error) {
315
+ this.close(error);
316
+ } finally {
317
+ this.delivering = false;
318
+ }
319
+ }
320
+
321
+ close(reason = new Error('远程连接中断,未确认的操作结果未知')) {
322
+ if (this.closed) return;
323
+ this.closed = true;
324
+ clearTimeout(this.scheduled);
325
+ clearTimeout(this.ackTimer);
326
+ clearTimeout(this.lease);
327
+ clearInterval(this.ackWatcher);
328
+ for (const item of this.queue) {
329
+ item.signal?.removeEventListener('abort', item.abort);
330
+ item.reject(reason);
331
+ }
332
+ this.queue.length = 0;
333
+ this.unacked.clear();
334
+ this.unackedBytes = 0;
335
+ this.queueBytes = 0;
336
+ this.received.clear();
337
+ this.onClose?.(reason);
338
+ }
339
+ }
340
+
341
+ // Each Relay socket sees one shared pacing budget across its logical streams.
342
+ export function relayPacer() {
343
+ let tokens = 64;
344
+ let last = performance.now();
345
+ return (type) => {
346
+ const now = performance.now();
347
+ tokens = Math.min(64, tokens + (now - last) * 0.3);
348
+ last = now;
349
+ if (tokens < (type === MSG_E2EE_CTRL ? 1 : 9)) return false;
350
+ tokens--;
351
+ return true;
352
+ };
353
+ }
354
+
355
+ export function createPath({ send, ready, bufferedAmount, close, highWater = 256 << 10 }) {
356
+ let start = Date.now();
357
+ let count = 0;
358
+ let size = 0;
359
+ let invalid = 0;
360
+ return {
361
+ send, ready, bufferedAmount, close, highWater,
362
+ accept(length) {
363
+ if (Date.now() - start >= 1000) {
364
+ start = Date.now();
365
+ count = 0;
366
+ size = 0;
367
+ }
368
+ size += length;
369
+ return ++count <= 512 && size <= (32 << 20);
370
+ },
371
+ invalid() {
372
+ if (++invalid >= 4) close();
373
+ },
374
+ };
375
+ }
@@ -0,0 +1,265 @@
1
+ import { generateLogicalSessionId, MSG_E2EE_BOX, MSG_E2EE_CTRL } from './e2ee.js';
2
+ import { createPath } from './multipath.js';
3
+
4
+ const STUN_DEFAULT = 'stun:stun.cloudflare.com:3478';
5
+ const PROBE_TIMEOUT = 5000;
6
+ const MAX_CANDIDATES = 32;
7
+ const MAX_SDP = 64 << 10;
8
+ const LABEL = 'dsh-remote-v2';
9
+
10
+ export function normalizeStun(value) {
11
+ if (value === 'none') return [];
12
+ const urls = value ? (Array.isArray(value) ? value : value.split(',')) : [STUN_DEFAULT];
13
+ if (urls.length > 4 || urls.some((url) => !/^stun:(?:[a-z0-9][a-z0-9.-]*|\[[a-f0-9:]+\])(?::[0-9]{1,5})?$/iu.test(url))) {
14
+ throw new Error('Invalid DSH_REMOTE_STUN server configuration');
15
+ }
16
+ return urls;
17
+ }
18
+
19
+ export function normalizeP2pEnabled(value) {
20
+ if (value === false || (typeof value === 'string' && ['0', 'false', 'off', 'none'].includes(value.trim().toLowerCase()))) {
21
+ return false;
22
+ }
23
+ return true;
24
+ }
25
+
26
+ export function localAddress(address) {
27
+ if (typeof address !== 'string' || !address) return false;
28
+ const bare = address.startsWith('[') && address.endsWith(']') ? address.slice(1, -1) : address;
29
+ const lower = bare.toLowerCase();
30
+ if (lower.endsWith('.local') || lower === '::1' || /^f[cd][0-9a-f]{2}:/u.test(lower) ||
31
+ /^fe[89ab][0-9a-f]:/u.test(lower)) return true;
32
+ const v4 = lower.startsWith('::ffff:') ? lower.slice(7) : lower;
33
+ const ip = v4.split('.').map(Number);
34
+ if (ip.length !== 4 || ip.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;
35
+ return ip[0] === 10 || ip[0] === 127 || (ip[0] === 192 && ip[1] === 168) ||
36
+ (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
37
+ (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) || (ip[0] === 169 && ip[1] === 254);
38
+ }
39
+
40
+ function safeCandidate(line, urls) {
41
+ if (typeof line !== 'string' || line.length > 1024 || /[\r\n]/u.test(line)) return false;
42
+ const fields = line.split(/ +/u);
43
+ const [foundation, component, protocol, , address, port, typ, kind] = fields;
44
+ return /^candidate:[A-Za-z0-9+\/]+$/u.test(foundation) && component === '1' &&
45
+ protocol?.toLowerCase() === 'udp' && typeof address === 'string' &&
46
+ /^(?:(?:[0-9]{1,3}\.){3}[0-9]{1,3}|[a-f0-9:]+:[a-f0-9:]+|[-a-z0-9.]+\.local)$/iu.test(address) &&
47
+ /^[1-9][0-9]{0,4}$/u.test(port) && Number(port) <= 65535 &&
48
+ typ === 'typ' && (kind === 'host' || (urls.length > 0 && (kind === 'srflx' || kind === 'prflx'))) &&
49
+ (urls.length > 0 || localAddress(address));
50
+ }
51
+
52
+ function sanitizeSdp(sdp, urls) {
53
+ if (typeof sdp !== 'string' || sdp.length > MAX_SDP) throw new Error('Invalid ICE description size');
54
+ let count = 0;
55
+ const lines = sdp.split(/\r?\n/u).filter((line) => {
56
+ if (!line.startsWith('a=candidate:')) return true;
57
+ ++count;
58
+ return count <= MAX_CANDIDATES && safeCandidate(line.slice(2), urls);
59
+ });
60
+ if (lines.filter((line) => line.startsWith('m=')).length !== 1 ||
61
+ !lines.some((line) => /^m=application \d+ UDP\/DTLS\/SCTP webrtc-datachannel$/u.test(line))) {
62
+ throw new Error('Unsupported WebRTC description');
63
+ }
64
+ return lines.join('\r\n');
65
+ }
66
+
67
+ export class PeerPath {
68
+ constructor(session, { createPeer, sendChannel, initiator, urls, onPath, signalPath, probeTimeout = PROBE_TIMEOUT }) {
69
+ this.session = session;
70
+ this.createPeer = createPeer;
71
+ this.sendChannel = sendChannel;
72
+ this.initiator = initiator;
73
+ this.urls = urls;
74
+ this.onPath = onPath;
75
+ this.signalPath = signalPath;
76
+ this.probeTimeout = probeTimeout;
77
+ this.epoch = 0;
78
+ }
79
+
80
+ async start() {
81
+ if (!this.initiator || this.current || this.session.closed) return;
82
+ const state = this.begin(this.epoch + 1);
83
+ this.bindChannel(state, state.pc.createDataChannel(LABEL, { ordered: true }));
84
+ try {
85
+ const offer = await state.pc.createOffer();
86
+ await state.pc.setLocalDescription(offer);
87
+ await this.sendDescription(state, 'p2p_offer');
88
+ } catch {
89
+ await this.stop(state);
90
+ }
91
+ }
92
+
93
+ begin(epoch) {
94
+ const pc = this.createPeer({ iceServers: this.urls.map((urls) => ({ urls })) });
95
+ const state = {
96
+ pc, epoch, count: 0, incoming: 0, queued: [], outgoing: [],
97
+ remoteReady: false, localReady: false, heard: Date.now(), probe: generateLogicalSessionId(),
98
+ };
99
+ this.epoch = epoch;
100
+ this.current = state;
101
+ state.timer = setTimeout(() => void this.stop(state), this.probeTimeout);
102
+ pc.onconnectionstatechange = () => {
103
+ if (['failed', 'closed', 'disconnected'].includes(pc.connectionState)) void this.stop(state);
104
+ };
105
+ pc.onicecandidate = ({ candidate }) => {
106
+ if (this.current !== state || !candidate || state.count >= MAX_CANDIDATES ||
107
+ !safeCandidate(candidate.candidate, this.urls)) return;
108
+ state.count++;
109
+ const row = {
110
+ candidate: candidate.candidate,
111
+ sdpMid: candidate.sdpMid,
112
+ sdpMLineIndex: candidate.sdpMLineIndex,
113
+ };
114
+ if (state.localReady) void this.signal(state, 'p2p_candidate', { candidate: row }).catch(() => this.stop(state));
115
+ else state.outgoing.push(row);
116
+ };
117
+ if (!this.initiator) pc.ondatachannel = ({ channel }) => this.bindChannel(state, channel);
118
+ return state;
119
+ }
120
+
121
+ signal(state, type, fields) {
122
+ return this.session.control({ type, epoch: state.epoch, ...fields }, this.signalPath());
123
+ }
124
+
125
+ async sendDescription(state, type) {
126
+ if (this.current !== state) return;
127
+ const sdp = sanitizeSdp(state.pc.localDescription.sdp, this.urls);
128
+ // Candidates gathered synchronously by werift are already in SDP.
129
+ const embedded = new Set(sdp.split('\r\n').filter((row) => row.startsWith('a=candidate:')).map((row) => row.slice(2)));
130
+ if (!await this.signal(state, type, { sdp })) throw new Error('Relay signaling is unavailable');
131
+ if (this.current !== state) return;
132
+ for (const candidate of state.outgoing.splice(0)) {
133
+ if (!embedded.has(candidate.candidate)) await this.signal(state, 'p2p_candidate', { candidate });
134
+ }
135
+ state.localReady = true;
136
+ }
137
+
138
+ bindChannel(state, channel) {
139
+ if (this.current !== state || state.channel || channel.label !== LABEL || !channel.ordered ||
140
+ channel.maxRetransmits != null || channel.maxPacketLifeTime != null) {
141
+ channel.close();
142
+ return;
143
+ }
144
+ state.channel = channel;
145
+ channel.binaryType = 'arraybuffer';
146
+ channel.bufferedAmountLowThreshold = 128 << 10;
147
+ const path = state.path = createPath({
148
+ ready: () => this.current === state && channel.readyState === 'open',
149
+ send: (kind, payload) => {
150
+ const packet = new Uint8Array(1 + payload.length);
151
+ packet[0] = kind;
152
+ packet.set(payload, 1);
153
+ this.sendChannel(channel, packet);
154
+ },
155
+ bufferedAmount: () => channel.bufferedAmount,
156
+ close: () => void this.stop(state),
157
+ highWater: 512 << 10,
158
+ });
159
+ channel.onmessage = ({ data }) => {
160
+ if (typeof data === 'string') return;
161
+ const bytes = new Uint8Array(data);
162
+ if (bytes[0] === MSG_E2EE_CTRL || bytes[0] === MSG_E2EE_BOX) this.session.receive(bytes[0], bytes.subarray(1), path);
163
+ };
164
+ channel.onopen = () => {
165
+ const limit = state.pc.sctp?.maxMessageSize;
166
+ if (typeof limit === 'number' && limit > 0 && limit < (33 << 10)) {
167
+ void this.stop(state);
168
+ return;
169
+ }
170
+ if (this.urls.length === 0) {
171
+ const iceConn = state.pc.sctp?.dtlsTransport?.iceTransport?.connection ?? state.pc.dtlsTransports?.[0]?.iceTransport?.connection;
172
+ const remotes = iceConn?._remoteCandidates ?? [];
173
+ const nomHost = iceConn?.nominated?.remoteCandidate?.host ?? iceConn?.nominated?.remoteAddr?.[0];
174
+ if (remotes.some((c) => !localAddress(c?.host)) || (nomHost !== undefined && !localAddress(nomHost))) {
175
+ void this.stop(state);
176
+ return;
177
+ }
178
+ }
179
+ const probe = () => {
180
+ if (Date.now() - state.heard >= 4000) {
181
+ void this.stop(state);
182
+ return;
183
+ }
184
+ void this.session.control({ type: 'path_probe', epoch: state.epoch, probe: state.probe }, path)
185
+ .catch(() => this.stop(state));
186
+ };
187
+ probe();
188
+ state.heartbeat = setInterval(probe, 2000);
189
+ };
190
+ channel.onclose = channel.onerror = () => void this.stop(state);
191
+ if (channel.readyState === 'open') channel.onopen();
192
+ }
193
+
194
+ async handle(message, path) {
195
+ const { type, epoch } = message;
196
+ if (!Number.isSafeInteger(epoch) || epoch <= 0) return;
197
+ let state = this.current;
198
+ if (type === 'p2p_offer' && !this.initiator && !state && epoch > this.epoch && path === this.signalPath()) {
199
+ const sdp = sanitizeSdp(message.sdp, this.urls);
200
+ state = this.begin(epoch);
201
+ try {
202
+ await state.pc.setRemoteDescription({ type: 'offer', sdp });
203
+ await this.flushCandidates(state);
204
+ const answer = await state.pc.createAnswer();
205
+ await state.pc.setLocalDescription(answer);
206
+ await this.sendDescription(state, 'p2p_answer');
207
+ } catch {
208
+ await this.stop(state);
209
+ }
210
+ return;
211
+ }
212
+ if (!state || state.epoch !== epoch) return;
213
+ if (type === 'p2p_answer' && this.initiator && !state.remoteReady && path === this.signalPath() && !state.answering) {
214
+ state.answering = true;
215
+ try {
216
+ await state.pc.setRemoteDescription({ type: 'answer', sdp: sanitizeSdp(message.sdp, this.urls) });
217
+ await this.flushCandidates(state);
218
+ } catch {
219
+ await this.stop(state);
220
+ }
221
+ } else if (type === 'p2p_candidate' && path === this.signalPath()) {
222
+ const remote = message.candidate;
223
+ if (!safeCandidate(remote?.candidate, this.urls) || ++state.incoming > MAX_CANDIDATES ||
224
+ (remote.sdpMLineIndex != null && remote.sdpMLineIndex !== 0)) return;
225
+ if (state.remoteReady) await state.pc.addIceCandidate(remote);
226
+ else state.queued.push(remote);
227
+ } else if (path === state.path && typeof message.probe === 'string' && /^[A-Za-z0-9_-]{22}$/u.test(message.probe)) {
228
+ if (type === 'path_probe') {
229
+ state.incomingProbe = true;
230
+ await this.session.control({ type: 'path_probe_ack', epoch, probe: message.probe }, path);
231
+ } else if (type === 'path_probe_ack' && message.probe === state.probe) {
232
+ state.heard = Date.now();
233
+ state.ack = true;
234
+ }
235
+ if (this.current === state && state.incomingProbe && state.ack && !state.promoted) {
236
+ state.promoted = true;
237
+ clearTimeout(state.timer);
238
+ this.session.setP2P(path);
239
+ this.onPath?.(true);
240
+ }
241
+ }
242
+ }
243
+
244
+ async flushCandidates(state) {
245
+ state.remoteReady = true;
246
+ for (const candidate of state.queued.splice(0)) await state.pc.addIceCandidate(candidate);
247
+ }
248
+
249
+ async stop(state = this.current) {
250
+ if (!state || this.current !== state) return;
251
+ this.current = null;
252
+ clearTimeout(state.timer);
253
+ clearInterval(state.heartbeat);
254
+ state.pc.onicecandidate = state.pc.onconnectionstatechange = state.pc.ondatachannel = null;
255
+ if (state.channel) {
256
+ state.channel.onopen = state.channel.onmessage = state.channel.onclose = state.channel.onerror = null;
257
+ state.channel.close();
258
+ }
259
+ if (state.promoted) {
260
+ this.session.setP2P(null);
261
+ this.onPath?.(false);
262
+ }
263
+ await state.pc.close();
264
+ }
265
+ }