@webvpn/client 0.0.0 → 0.5.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/LICENSE +21 -0
- package/README.md +40 -1
- package/build/address.d.ts +12 -0
- package/build/connect.d.ts +32 -0
- package/build/context.d.ts +136 -0
- package/build/dns.d.ts +18 -0
- package/build/index.d.ts +11 -0
- package/build/index.js +1935 -0
- package/build/listener.d.ts +22 -0
- package/build/protocol/codes.d.ts +62 -0
- package/build/protocol/control.d.ts +204 -0
- package/build/protocol/index.d.ts +11 -0
- package/build/protocol/mux.d.ts +32 -0
- package/build/protocol/options.d.ts +69 -0
- package/build/protocol/udp.d.ts +19 -0
- package/build/protocol/wire.d.ts +35 -0
- package/build/session.d.ts +49 -0
- package/build/tcp.d.ts +32 -0
- package/build/udp.d.ts +38 -0
- package/build/websocket.d.ts +7 -0
- package/build/webtransport.d.ts +6 -0
- package/package.json +39 -2
package/build/index.js
ADDED
|
@@ -0,0 +1,1935 @@
|
|
|
1
|
+
import { createWritable, setOutgoingMaxBufferedDatagrams } from "@banou/ponyfill/webtransport";
|
|
2
|
+
// src/protocol/codes.ts
|
|
3
|
+
/** What a relay offers, as the bits of a hello's `features`. A client sends a request only when its bit is set. */
|
|
4
|
+
var Feature = {
|
|
5
|
+
/** `tcpListen` and `tcpUnlisten`. */
|
|
6
|
+
LISTEN: 1,
|
|
7
|
+
/** `dnsQuery` and `tcpConnectName`. */
|
|
8
|
+
DNS: 2,
|
|
9
|
+
/** `auth` and `authClear`. */
|
|
10
|
+
AUTH: 4,
|
|
11
|
+
/** Socket requests are answered `AUTH_REQUIRED` until an `auth` succeeded. */
|
|
12
|
+
AUTH_REQUIRED: 8
|
|
13
|
+
};
|
|
14
|
+
/** Why a request failed, as an `error` reply carries it. A code not named here is treated as `OTHER`. */
|
|
15
|
+
var ErrorCode = {
|
|
16
|
+
/** The relay does not know the request or the option, or has the feature off. */
|
|
17
|
+
UNSUPPORTED: 1,
|
|
18
|
+
/** The relay's policy refuses this target, port or option. */
|
|
19
|
+
REFUSED: 2,
|
|
20
|
+
/** A limit is reached; the same request may pass later. */
|
|
21
|
+
CAPACITY: 3,
|
|
22
|
+
/** The socket has too many requests waiting; nothing was applied. */
|
|
23
|
+
BUSY: 4,
|
|
24
|
+
AUTH_REQUIRED: 5,
|
|
25
|
+
/** The credential was not accepted; the session is as it was. */
|
|
26
|
+
AUTH_FAILED: 6,
|
|
27
|
+
UNKNOWN_SOCKET: 7,
|
|
28
|
+
/** The relay could not open the socket's stream in time: the session has no room for more streams, and a new session has. */
|
|
29
|
+
NO_STREAM: 8,
|
|
30
|
+
CONNECTION_REFUSED: 16,
|
|
31
|
+
TIMED_OUT: 17,
|
|
32
|
+
HOST_UNREACHABLE: 18,
|
|
33
|
+
NETWORK_UNREACHABLE: 19,
|
|
34
|
+
CONNECTION_RESET: 20,
|
|
35
|
+
ADDRESS_IN_USE: 21,
|
|
36
|
+
ADDRESS_NOT_AVAILABLE: 22,
|
|
37
|
+
/** The name has no address. */
|
|
38
|
+
NAME_NOT_FOUND: 23,
|
|
39
|
+
/** The resolver did not answer. */
|
|
40
|
+
LOOKUP_FAILED: 24,
|
|
41
|
+
/** The message says what happened. */
|
|
42
|
+
OTHER: 65535
|
|
43
|
+
};
|
|
44
|
+
/** The code a session is closed with. */
|
|
45
|
+
var CloseCode = {
|
|
46
|
+
NORMAL: 0,
|
|
47
|
+
/** A frame could not be read, or setup did not finish in time. */
|
|
48
|
+
PROTOCOL_ERROR: 1,
|
|
49
|
+
VERSION_MISMATCH: 2,
|
|
50
|
+
SESSION_LIMIT: 3,
|
|
51
|
+
/** The relay is stopping; another session may be opened at once. */
|
|
52
|
+
RESTARTING: 4,
|
|
53
|
+
/** Never sent: the carrier ended with neither a `bye` nor a close code, as a lost connection does. */
|
|
54
|
+
LOST: 5
|
|
55
|
+
};
|
|
56
|
+
/** The WebSocket close code that carries a session close code. */
|
|
57
|
+
var websocketCloseCode = (code) => 4e3 + code;
|
|
58
|
+
/** The code the relay resets its side of a socket's stream with. */
|
|
59
|
+
var ResetCode = {
|
|
60
|
+
/** The client closed the socket. */
|
|
61
|
+
CLOSED: 0,
|
|
62
|
+
/** The peer reset the connection. */
|
|
63
|
+
PEER_RESET: 1
|
|
64
|
+
};
|
|
65
|
+
// src/protocol/options.ts
|
|
66
|
+
var sized = (bytes, length) => {
|
|
67
|
+
if (bytes.byteLength !== length) throw new TypeError(`expected ${length} bytes, not ${bytes.byteLength}`);
|
|
68
|
+
return bytes;
|
|
69
|
+
};
|
|
70
|
+
var putTcpOption = (w, option) => {
|
|
71
|
+
switch (option.type) {
|
|
72
|
+
case "noDelay": return w.u8(0).bool(option.value);
|
|
73
|
+
case "ttl": return w.u8(1).u32(option.value);
|
|
74
|
+
case "keepAlive": return w.u8(2).bool(option.enabled).u32(option.initialDelaySeconds);
|
|
75
|
+
case "sendBufferSize": return w.u8(3).u32(option.value);
|
|
76
|
+
case "recvBufferSize": return w.u8(4).u32(option.value);
|
|
77
|
+
case "unknown": return w.u8(option.tag);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
var readTcpOption = (r) => {
|
|
81
|
+
const tag = r.u8();
|
|
82
|
+
switch (tag) {
|
|
83
|
+
case 0: return {
|
|
84
|
+
type: "noDelay",
|
|
85
|
+
value: r.bool()
|
|
86
|
+
};
|
|
87
|
+
case 1: return {
|
|
88
|
+
type: "ttl",
|
|
89
|
+
value: r.u32()
|
|
90
|
+
};
|
|
91
|
+
case 2: return {
|
|
92
|
+
type: "keepAlive",
|
|
93
|
+
enabled: r.bool(),
|
|
94
|
+
initialDelaySeconds: r.u32()
|
|
95
|
+
};
|
|
96
|
+
case 3: return {
|
|
97
|
+
type: "sendBufferSize",
|
|
98
|
+
value: r.u32()
|
|
99
|
+
};
|
|
100
|
+
case 4: return {
|
|
101
|
+
type: "recvBufferSize",
|
|
102
|
+
value: r.u32()
|
|
103
|
+
};
|
|
104
|
+
default: return {
|
|
105
|
+
type: "unknown",
|
|
106
|
+
tag
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var putUdpOption = (w, option) => {
|
|
111
|
+
switch (option.type) {
|
|
112
|
+
case "broadcast": return w.u8(0).bool(option.value);
|
|
113
|
+
case "ttl": return w.u8(1).u32(option.value);
|
|
114
|
+
case "multicastTtlV4": return w.u8(2).u32(option.value);
|
|
115
|
+
case "multicastLoopV4": return w.u8(3).bool(option.value);
|
|
116
|
+
case "multicastLoopV6": return w.u8(4).bool(option.value);
|
|
117
|
+
case "addMembershipV4":
|
|
118
|
+
case "dropMembershipV4": return w.u8(option.type === "addMembershipV4" ? 5 : 6).put(sized(option.group, 4)).put(sized(option.interface, 4));
|
|
119
|
+
case "addMembershipV6":
|
|
120
|
+
case "dropMembershipV6": return w.u8(option.type === "addMembershipV6" ? 7 : 8).put(sized(option.group, 16)).u32(option.interface);
|
|
121
|
+
case "sendBufferSize": return w.u8(9).u32(option.value);
|
|
122
|
+
case "recvBufferSize": return w.u8(10).u32(option.value);
|
|
123
|
+
case "unknown": return w.u8(option.tag);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
var readUdpOption = (r) => {
|
|
127
|
+
const tag = r.u8();
|
|
128
|
+
switch (tag) {
|
|
129
|
+
case 0: return {
|
|
130
|
+
type: "broadcast",
|
|
131
|
+
value: r.bool()
|
|
132
|
+
};
|
|
133
|
+
case 1: return {
|
|
134
|
+
type: "ttl",
|
|
135
|
+
value: r.u32()
|
|
136
|
+
};
|
|
137
|
+
case 2: return {
|
|
138
|
+
type: "multicastTtlV4",
|
|
139
|
+
value: r.u32()
|
|
140
|
+
};
|
|
141
|
+
case 3: return {
|
|
142
|
+
type: "multicastLoopV4",
|
|
143
|
+
value: r.bool()
|
|
144
|
+
};
|
|
145
|
+
case 4: return {
|
|
146
|
+
type: "multicastLoopV6",
|
|
147
|
+
value: r.bool()
|
|
148
|
+
};
|
|
149
|
+
case 5:
|
|
150
|
+
case 6: return {
|
|
151
|
+
type: tag === 5 ? "addMembershipV4" : "dropMembershipV4",
|
|
152
|
+
group: r.take(4).slice(),
|
|
153
|
+
interface: r.take(4).slice()
|
|
154
|
+
};
|
|
155
|
+
case 7:
|
|
156
|
+
case 8: return {
|
|
157
|
+
type: tag === 7 ? "addMembershipV6" : "dropMembershipV6",
|
|
158
|
+
group: r.take(16).slice(),
|
|
159
|
+
interface: r.u32()
|
|
160
|
+
};
|
|
161
|
+
case 9: return {
|
|
162
|
+
type: "sendBufferSize",
|
|
163
|
+
value: r.u32()
|
|
164
|
+
};
|
|
165
|
+
case 10: return {
|
|
166
|
+
type: "recvBufferSize",
|
|
167
|
+
value: r.u32()
|
|
168
|
+
};
|
|
169
|
+
default: return {
|
|
170
|
+
type: "unknown",
|
|
171
|
+
tag
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
// src/protocol/wire.ts
|
|
176
|
+
/** Bytes that are not laid out as the protocol says. It ends the session. */
|
|
177
|
+
var ProtocolError = class extends Error {
|
|
178
|
+
constructor(message) {
|
|
179
|
+
super(message);
|
|
180
|
+
this.name = "ProtocolError";
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
var addressFamily = (ip) => {
|
|
184
|
+
if (ip.byteLength === 4) return 0;
|
|
185
|
+
if (ip.byteLength === 16) return 1;
|
|
186
|
+
throw new TypeError(`an address holds 4 or 16 bytes, not ${ip.byteLength}`);
|
|
187
|
+
};
|
|
188
|
+
/** Reads fields off `bytes` in order. `take` and `rest` return views into `bytes`, not copies. */
|
|
189
|
+
var reader = (bytes) => {
|
|
190
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
191
|
+
let at = 0;
|
|
192
|
+
const advance = (length) => {
|
|
193
|
+
if (at + length > bytes.byteLength) throw new ProtocolError("a body ends before its fields do");
|
|
194
|
+
at += length;
|
|
195
|
+
return at - length;
|
|
196
|
+
};
|
|
197
|
+
const take = (length) => {
|
|
198
|
+
const from = advance(length);
|
|
199
|
+
return bytes.subarray(from, from + length);
|
|
200
|
+
};
|
|
201
|
+
const u8 = () => view.getUint8(advance(1));
|
|
202
|
+
const u16 = () => view.getUint16(advance(2));
|
|
203
|
+
const optionalAddress = () => {
|
|
204
|
+
const family = u8();
|
|
205
|
+
if (family === 2) return void 0;
|
|
206
|
+
if (family > 2) throw new ProtocolError("unknown address family");
|
|
207
|
+
return {
|
|
208
|
+
ip: take(family === 0 ? 4 : 16).slice(),
|
|
209
|
+
port: u16()
|
|
210
|
+
};
|
|
211
|
+
};
|
|
212
|
+
return {
|
|
213
|
+
u8,
|
|
214
|
+
u16,
|
|
215
|
+
u32: () => view.getUint32(advance(4)),
|
|
216
|
+
bool: () => u8() !== 0,
|
|
217
|
+
take,
|
|
218
|
+
rest: () => take(bytes.byteLength - at),
|
|
219
|
+
left: () => bytes.byteLength - at,
|
|
220
|
+
optionalAddress,
|
|
221
|
+
address: () => {
|
|
222
|
+
const address = optionalAddress();
|
|
223
|
+
if (!address) throw new ProtocolError("an address is required here");
|
|
224
|
+
return address;
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
};
|
|
228
|
+
var writer = () => {
|
|
229
|
+
let bytes = /* @__PURE__ */ new Uint8Array(64);
|
|
230
|
+
let view = new DataView(bytes.buffer);
|
|
231
|
+
let length = 0;
|
|
232
|
+
const advance = (more) => {
|
|
233
|
+
if (length + more > bytes.byteLength) {
|
|
234
|
+
const grown = new Uint8Array(Math.max(bytes.byteLength * 2, length + more));
|
|
235
|
+
grown.set(bytes.subarray(0, length));
|
|
236
|
+
bytes = grown;
|
|
237
|
+
view = new DataView(grown.buffer);
|
|
238
|
+
}
|
|
239
|
+
length += more;
|
|
240
|
+
return length - more;
|
|
241
|
+
};
|
|
242
|
+
const self = {
|
|
243
|
+
u8: (value) => {
|
|
244
|
+
const at = advance(1);
|
|
245
|
+
view.setUint8(at, value);
|
|
246
|
+
return self;
|
|
247
|
+
},
|
|
248
|
+
bool: (value) => self.u8(value ? 1 : 0),
|
|
249
|
+
u16: (value) => {
|
|
250
|
+
const at = advance(2);
|
|
251
|
+
view.setUint16(at, value);
|
|
252
|
+
return self;
|
|
253
|
+
},
|
|
254
|
+
u32: (value) => {
|
|
255
|
+
const at = advance(4);
|
|
256
|
+
view.setUint32(at, value);
|
|
257
|
+
return self;
|
|
258
|
+
},
|
|
259
|
+
put: (source) => {
|
|
260
|
+
const at = advance(source.byteLength);
|
|
261
|
+
bytes.set(source, at);
|
|
262
|
+
return self;
|
|
263
|
+
},
|
|
264
|
+
address: (address) => {
|
|
265
|
+
if (!address) return self.u8(2);
|
|
266
|
+
return self.u8(addressFamily(address.ip)).put(address.ip).u16(address.port);
|
|
267
|
+
},
|
|
268
|
+
setU32: (at, value) => {
|
|
269
|
+
view.setUint32(at, value);
|
|
270
|
+
return self;
|
|
271
|
+
},
|
|
272
|
+
length: () => length,
|
|
273
|
+
done: () => bytes.slice(0, length)
|
|
274
|
+
};
|
|
275
|
+
return self;
|
|
276
|
+
};
|
|
277
|
+
// src/protocol/control.ts
|
|
278
|
+
/** The version this package speaks. While the major is 0, peers need the same minor. */
|
|
279
|
+
var VERSION = {
|
|
280
|
+
major: 0,
|
|
281
|
+
minor: 1
|
|
282
|
+
};
|
|
283
|
+
/** The longest frame body a relay reads from a client. */
|
|
284
|
+
var MAX_CLIENT_FRAME_BYTES = 4096;
|
|
285
|
+
/** The longest frame body a client reads from a relay; a whole DNS answer fits. */
|
|
286
|
+
var MAX_RELAY_FRAME_BYTES = 131072;
|
|
287
|
+
/** The longest agent a hello carries; a longer one is cut when it is written. */
|
|
288
|
+
var MAX_AGENT_BYTES = 255;
|
|
289
|
+
var HEADER_BYTES$1 = 5;
|
|
290
|
+
var MAGIC = Uint8Array.of(87, 86, 80, 78);
|
|
291
|
+
var encoder$1 = new TextEncoder();
|
|
292
|
+
var decoder = new TextDecoder();
|
|
293
|
+
/** A hello at this package's version. */
|
|
294
|
+
var hello = (features, agent) => ({
|
|
295
|
+
type: "hello",
|
|
296
|
+
...VERSION,
|
|
297
|
+
features,
|
|
298
|
+
agent
|
|
299
|
+
});
|
|
300
|
+
/** Whether this package can speak to the peer that sent `peer`. */
|
|
301
|
+
var compatible = (peer) => peer.major === VERSION.major && (peer.major !== 0 || peer.minor === VERSION.minor);
|
|
302
|
+
var CLIENT = {
|
|
303
|
+
hello: 0,
|
|
304
|
+
auth: 1,
|
|
305
|
+
authClear: 2,
|
|
306
|
+
tcpConnect: 16,
|
|
307
|
+
tcpConnectName: 17,
|
|
308
|
+
tcpClose: 18,
|
|
309
|
+
tcpReset: 19,
|
|
310
|
+
tcpSetOption: 20,
|
|
311
|
+
tcpListen: 32,
|
|
312
|
+
tcpUnlisten: 33,
|
|
313
|
+
udpBind: 48,
|
|
314
|
+
udpClose: 49,
|
|
315
|
+
udpConnect: 50,
|
|
316
|
+
udpDisconnect: 51,
|
|
317
|
+
udpSetOption: 52,
|
|
318
|
+
dnsQuery: 64
|
|
319
|
+
};
|
|
320
|
+
var RELAY = {
|
|
321
|
+
hello: 0,
|
|
322
|
+
ok: 1,
|
|
323
|
+
error: 2,
|
|
324
|
+
socket: 3,
|
|
325
|
+
dnsAnswer: 4,
|
|
326
|
+
accepted: 16,
|
|
327
|
+
acceptRefused: 17,
|
|
328
|
+
closed: 18,
|
|
329
|
+
draining: 32,
|
|
330
|
+
bye: 33
|
|
331
|
+
};
|
|
332
|
+
var putHello = (w, packet) => {
|
|
333
|
+
let agent = encoder$1.encode(packet.agent);
|
|
334
|
+
if (agent.byteLength > 255) {
|
|
335
|
+
let end = 255;
|
|
336
|
+
while ((agent[end] & 192) === 128) end--;
|
|
337
|
+
agent = agent.subarray(0, end);
|
|
338
|
+
}
|
|
339
|
+
w.put(MAGIC).u8(packet.major).u8(packet.minor).u32(packet.features).put(agent);
|
|
340
|
+
};
|
|
341
|
+
var readHello = (r) => {
|
|
342
|
+
const magic = r.take(MAGIC.byteLength);
|
|
343
|
+
if (MAGIC.some((byte, at) => magic[at] !== byte)) throw new ProtocolError("not a WebVPN hello");
|
|
344
|
+
return {
|
|
345
|
+
type: "hello",
|
|
346
|
+
major: r.u8(),
|
|
347
|
+
minor: r.u8(),
|
|
348
|
+
features: r.u32(),
|
|
349
|
+
agent: decoder.decode(r.rest().subarray(0, 255))
|
|
350
|
+
};
|
|
351
|
+
};
|
|
352
|
+
var open = (kind) => writer().u8(kind).u32(0);
|
|
353
|
+
var seal = (w) => w.setU32(1, w.length() - HEADER_BYTES$1).done();
|
|
354
|
+
var split = (bytes, limit) => {
|
|
355
|
+
if (bytes.byteLength < HEADER_BYTES$1) return void 0;
|
|
356
|
+
const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1);
|
|
357
|
+
if (length > limit) throw new ProtocolError("a length is over the limit");
|
|
358
|
+
const taken = HEADER_BYTES$1 + length;
|
|
359
|
+
if (bytes.byteLength < taken) return void 0;
|
|
360
|
+
return {
|
|
361
|
+
kind: bytes[0],
|
|
362
|
+
body: reader(bytes.subarray(HEADER_BYTES$1, taken)),
|
|
363
|
+
taken
|
|
364
|
+
};
|
|
365
|
+
};
|
|
366
|
+
/** The packet as one frame. */
|
|
367
|
+
var encodeClientPacket = (packet) => {
|
|
368
|
+
const w = open(packet.type === "unknown" ? packet.kind : CLIENT[packet.type]);
|
|
369
|
+
switch (packet.type) {
|
|
370
|
+
case "hello":
|
|
371
|
+
putHello(w, packet);
|
|
372
|
+
break;
|
|
373
|
+
case "auth":
|
|
374
|
+
w.u32(packet.id).put(packet.credential);
|
|
375
|
+
break;
|
|
376
|
+
case "authClear":
|
|
377
|
+
w.u32(packet.id);
|
|
378
|
+
break;
|
|
379
|
+
case "tcpConnect":
|
|
380
|
+
w.u32(packet.id).address(packet.remote);
|
|
381
|
+
break;
|
|
382
|
+
case "tcpConnectName":
|
|
383
|
+
w.u32(packet.id).u16(packet.port).put(packet.query);
|
|
384
|
+
break;
|
|
385
|
+
case "tcpClose":
|
|
386
|
+
case "tcpReset":
|
|
387
|
+
case "tcpUnlisten":
|
|
388
|
+
case "udpClose":
|
|
389
|
+
case "udpDisconnect":
|
|
390
|
+
w.u32(packet.id).u32(packet.socket);
|
|
391
|
+
break;
|
|
392
|
+
case "tcpSetOption":
|
|
393
|
+
putTcpOption(w.u32(packet.id).u32(packet.socket), packet.option);
|
|
394
|
+
break;
|
|
395
|
+
case "tcpListen":
|
|
396
|
+
case "udpBind":
|
|
397
|
+
w.u32(packet.id).address(packet.local);
|
|
398
|
+
break;
|
|
399
|
+
case "udpConnect":
|
|
400
|
+
w.u32(packet.id).u32(packet.socket).address(packet.remote);
|
|
401
|
+
break;
|
|
402
|
+
case "udpSetOption":
|
|
403
|
+
putUdpOption(w.u32(packet.id).u32(packet.socket), packet.option);
|
|
404
|
+
break;
|
|
405
|
+
case "dnsQuery":
|
|
406
|
+
w.u32(packet.id).put(packet.query);
|
|
407
|
+
break;
|
|
408
|
+
case "unknown": if (packet.id !== void 0) w.u32(packet.id);
|
|
409
|
+
}
|
|
410
|
+
return seal(w);
|
|
411
|
+
};
|
|
412
|
+
var readClientPacket = (kind, r) => {
|
|
413
|
+
switch (kind) {
|
|
414
|
+
case CLIENT.hello: return readHello(r);
|
|
415
|
+
case CLIENT.auth: return {
|
|
416
|
+
type: "auth",
|
|
417
|
+
id: r.u32(),
|
|
418
|
+
credential: r.rest().slice()
|
|
419
|
+
};
|
|
420
|
+
case CLIENT.authClear: return {
|
|
421
|
+
type: "authClear",
|
|
422
|
+
id: r.u32()
|
|
423
|
+
};
|
|
424
|
+
case CLIENT.tcpConnect: return {
|
|
425
|
+
type: "tcpConnect",
|
|
426
|
+
id: r.u32(),
|
|
427
|
+
remote: r.address()
|
|
428
|
+
};
|
|
429
|
+
case CLIENT.tcpConnectName: return {
|
|
430
|
+
type: "tcpConnectName",
|
|
431
|
+
id: r.u32(),
|
|
432
|
+
port: r.u16(),
|
|
433
|
+
query: r.rest().slice()
|
|
434
|
+
};
|
|
435
|
+
case CLIENT.tcpClose: return {
|
|
436
|
+
type: "tcpClose",
|
|
437
|
+
id: r.u32(),
|
|
438
|
+
socket: r.u32()
|
|
439
|
+
};
|
|
440
|
+
case CLIENT.tcpReset: return {
|
|
441
|
+
type: "tcpReset",
|
|
442
|
+
id: r.u32(),
|
|
443
|
+
socket: r.u32()
|
|
444
|
+
};
|
|
445
|
+
case CLIENT.tcpSetOption: return {
|
|
446
|
+
type: "tcpSetOption",
|
|
447
|
+
id: r.u32(),
|
|
448
|
+
socket: r.u32(),
|
|
449
|
+
option: readTcpOption(r)
|
|
450
|
+
};
|
|
451
|
+
case CLIENT.tcpListen: return {
|
|
452
|
+
type: "tcpListen",
|
|
453
|
+
id: r.u32(),
|
|
454
|
+
local: r.address()
|
|
455
|
+
};
|
|
456
|
+
case CLIENT.tcpUnlisten: return {
|
|
457
|
+
type: "tcpUnlisten",
|
|
458
|
+
id: r.u32(),
|
|
459
|
+
socket: r.u32()
|
|
460
|
+
};
|
|
461
|
+
case CLIENT.udpBind: return {
|
|
462
|
+
type: "udpBind",
|
|
463
|
+
id: r.u32(),
|
|
464
|
+
local: r.address()
|
|
465
|
+
};
|
|
466
|
+
case CLIENT.udpClose: return {
|
|
467
|
+
type: "udpClose",
|
|
468
|
+
id: r.u32(),
|
|
469
|
+
socket: r.u32()
|
|
470
|
+
};
|
|
471
|
+
case CLIENT.udpConnect: return {
|
|
472
|
+
type: "udpConnect",
|
|
473
|
+
id: r.u32(),
|
|
474
|
+
socket: r.u32(),
|
|
475
|
+
remote: r.address()
|
|
476
|
+
};
|
|
477
|
+
case CLIENT.udpDisconnect: return {
|
|
478
|
+
type: "udpDisconnect",
|
|
479
|
+
id: r.u32(),
|
|
480
|
+
socket: r.u32()
|
|
481
|
+
};
|
|
482
|
+
case CLIENT.udpSetOption: return {
|
|
483
|
+
type: "udpSetOption",
|
|
484
|
+
id: r.u32(),
|
|
485
|
+
socket: r.u32(),
|
|
486
|
+
option: readUdpOption(r)
|
|
487
|
+
};
|
|
488
|
+
case CLIENT.dnsQuery: return {
|
|
489
|
+
type: "dnsQuery",
|
|
490
|
+
id: r.u32(),
|
|
491
|
+
query: r.rest().slice()
|
|
492
|
+
};
|
|
493
|
+
default: return {
|
|
494
|
+
type: "unknown",
|
|
495
|
+
kind,
|
|
496
|
+
id: r.left() >= 4 ? r.u32() : void 0
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
/**
|
|
501
|
+
* Reads one packet off the front of `bytes`: the packet and how many bytes it took, or `undefined` until a whole
|
|
502
|
+
* frame is there. The packet holds copies, so `bytes` may be reused.
|
|
503
|
+
*/
|
|
504
|
+
var decodeClientPacket = (bytes) => {
|
|
505
|
+
const frame = split(bytes, MAX_CLIENT_FRAME_BYTES);
|
|
506
|
+
return frame && {
|
|
507
|
+
packet: readClientPacket(frame.kind, frame.body),
|
|
508
|
+
taken: frame.taken
|
|
509
|
+
};
|
|
510
|
+
};
|
|
511
|
+
/** The packet as one frame. */
|
|
512
|
+
var encodeRelayPacket = (packet) => {
|
|
513
|
+
const w = open(packet.type === "unknown" ? packet.kind : RELAY[packet.type]);
|
|
514
|
+
switch (packet.type) {
|
|
515
|
+
case "hello":
|
|
516
|
+
putHello(w, packet);
|
|
517
|
+
break;
|
|
518
|
+
case "ok":
|
|
519
|
+
w.u32(packet.id);
|
|
520
|
+
break;
|
|
521
|
+
case "error":
|
|
522
|
+
w.u32(packet.id).u16(packet.code).put(encoder$1.encode(packet.message));
|
|
523
|
+
break;
|
|
524
|
+
case "socket":
|
|
525
|
+
w.u32(packet.id).u32(packet.socket).address(packet.local).address(packet.remote);
|
|
526
|
+
break;
|
|
527
|
+
case "dnsAnswer":
|
|
528
|
+
w.u32(packet.id).put(packet.answer);
|
|
529
|
+
break;
|
|
530
|
+
case "accepted":
|
|
531
|
+
w.u32(packet.listener).u32(packet.socket).address(packet.local).address(packet.remote);
|
|
532
|
+
break;
|
|
533
|
+
case "acceptRefused":
|
|
534
|
+
w.u32(packet.listener).u16(packet.code).address(packet.remote);
|
|
535
|
+
break;
|
|
536
|
+
case "closed":
|
|
537
|
+
w.u32(packet.socket).u16(packet.code);
|
|
538
|
+
break;
|
|
539
|
+
case "bye": w.u32(packet.code).put(encoder$1.encode(packet.reason));
|
|
540
|
+
}
|
|
541
|
+
return seal(w);
|
|
542
|
+
};
|
|
543
|
+
var readRelayPacket = (kind, r) => {
|
|
544
|
+
switch (kind) {
|
|
545
|
+
case RELAY.hello: return readHello(r);
|
|
546
|
+
case RELAY.ok: return {
|
|
547
|
+
type: "ok",
|
|
548
|
+
id: r.u32()
|
|
549
|
+
};
|
|
550
|
+
case RELAY.error: return {
|
|
551
|
+
type: "error",
|
|
552
|
+
id: r.u32(),
|
|
553
|
+
code: r.u16(),
|
|
554
|
+
message: decoder.decode(r.rest())
|
|
555
|
+
};
|
|
556
|
+
case RELAY.socket: return {
|
|
557
|
+
type: "socket",
|
|
558
|
+
id: r.u32(),
|
|
559
|
+
socket: r.u32(),
|
|
560
|
+
local: r.address(),
|
|
561
|
+
remote: r.optionalAddress()
|
|
562
|
+
};
|
|
563
|
+
case RELAY.dnsAnswer: return {
|
|
564
|
+
type: "dnsAnswer",
|
|
565
|
+
id: r.u32(),
|
|
566
|
+
answer: r.rest().slice()
|
|
567
|
+
};
|
|
568
|
+
case RELAY.accepted: return {
|
|
569
|
+
type: "accepted",
|
|
570
|
+
listener: r.u32(),
|
|
571
|
+
socket: r.u32(),
|
|
572
|
+
local: r.address(),
|
|
573
|
+
remote: r.address()
|
|
574
|
+
};
|
|
575
|
+
case RELAY.acceptRefused: return {
|
|
576
|
+
type: "acceptRefused",
|
|
577
|
+
listener: r.u32(),
|
|
578
|
+
code: r.u16(),
|
|
579
|
+
remote: r.address()
|
|
580
|
+
};
|
|
581
|
+
case RELAY.closed: return {
|
|
582
|
+
type: "closed",
|
|
583
|
+
socket: r.u32(),
|
|
584
|
+
code: r.u16()
|
|
585
|
+
};
|
|
586
|
+
case RELAY.draining: return { type: "draining" };
|
|
587
|
+
case RELAY.bye: return {
|
|
588
|
+
type: "bye",
|
|
589
|
+
code: r.u32(),
|
|
590
|
+
reason: decoder.decode(r.rest())
|
|
591
|
+
};
|
|
592
|
+
default: return {
|
|
593
|
+
type: "unknown",
|
|
594
|
+
kind
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
/**
|
|
599
|
+
* Reads one packet off the front of `bytes`: the packet and how many bytes it took, or `undefined` until a whole
|
|
600
|
+
* frame is there. The packet holds copies, so `bytes` may be reused.
|
|
601
|
+
*/
|
|
602
|
+
var decodeRelayPacket = (bytes) => {
|
|
603
|
+
const frame = split(bytes, MAX_RELAY_FRAME_BYTES);
|
|
604
|
+
return frame && {
|
|
605
|
+
packet: readRelayPacket(frame.kind, frame.body),
|
|
606
|
+
taken: frame.taken
|
|
607
|
+
};
|
|
608
|
+
};
|
|
609
|
+
// src/protocol/mux.ts
|
|
610
|
+
/** The control stream of the WebSocket mux. It is never opened and never credited. */
|
|
611
|
+
var CONTROL_STREAM = 0;
|
|
612
|
+
var HEADER_BYTES = 5;
|
|
613
|
+
var EMPTY$1 = /* @__PURE__ */ new Uint8Array(0);
|
|
614
|
+
/** The kinds of the frame that carries a session's streams over one WebSocket: `[u8 kind][u32 stream][payload]`. */
|
|
615
|
+
var MuxKind = {
|
|
616
|
+
/** Relay only: a new stream, with one `MuxStreamType` byte. */
|
|
617
|
+
OPEN: 0,
|
|
618
|
+
DATA: 1,
|
|
619
|
+
/** This side of the stream is finished. */
|
|
620
|
+
FIN: 2,
|
|
621
|
+
/** Empty, or the `u32` code a stream reset carries. */
|
|
622
|
+
RESET: 3,
|
|
623
|
+
/** Client only: one `UdpPacket`, on stream 0. */
|
|
624
|
+
DATAGRAM: 4,
|
|
625
|
+
/** Client only: a `u32` of further bytes the relay may send on the stream. */
|
|
626
|
+
CREDIT: 5
|
|
627
|
+
};
|
|
628
|
+
/** What an `OPEN` frame says the stream carries. */
|
|
629
|
+
var MuxStreamType = {
|
|
630
|
+
TCP: 0,
|
|
631
|
+
/** A UDP socket's datagrams toward the client. */
|
|
632
|
+
UDP_DOWNLOAD: 1
|
|
633
|
+
};
|
|
634
|
+
var encodeMuxFrame = (kind, stream, payload = EMPTY$1) => {
|
|
635
|
+
const frame = new Uint8Array(HEADER_BYTES + payload.byteLength);
|
|
636
|
+
frame[0] = kind;
|
|
637
|
+
new DataView(frame.buffer).setUint32(1, stream);
|
|
638
|
+
frame.set(payload, HEADER_BYTES);
|
|
639
|
+
return frame;
|
|
640
|
+
};
|
|
641
|
+
/**
|
|
642
|
+
* The kind, stream and payload of one WebSocket message, or `undefined` for a message too short to be a frame, which
|
|
643
|
+
* a receiver ignores. `payload` is a view into `message`, not a copy.
|
|
644
|
+
*/
|
|
645
|
+
var decodeMuxFrame = (message) => {
|
|
646
|
+
if (message.byteLength < HEADER_BYTES) return void 0;
|
|
647
|
+
const stream = new DataView(message.buffer, message.byteOffset, message.byteLength).getUint32(1);
|
|
648
|
+
return {
|
|
649
|
+
kind: message[0],
|
|
650
|
+
stream,
|
|
651
|
+
payload: message.subarray(HEADER_BYTES)
|
|
652
|
+
};
|
|
653
|
+
};
|
|
654
|
+
// src/protocol/udp.ts
|
|
655
|
+
/** The longest payload a `UdpPacket` carries. */
|
|
656
|
+
var MAX_UDP_PAYLOAD_BYTES = 65536;
|
|
657
|
+
var size = (packet) => 4 + (packet.remote ? 1 + packet.remote.ip.byteLength + 2 : 1) + 4 + packet.data.byteLength;
|
|
658
|
+
var put = (packet, out, from) => {
|
|
659
|
+
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
|
|
660
|
+
let at = from;
|
|
661
|
+
view.setUint32(at, packet.socket);
|
|
662
|
+
at += 4;
|
|
663
|
+
if (packet.remote) {
|
|
664
|
+
const { ip, port } = packet.remote;
|
|
665
|
+
out[at] = addressFamily(ip);
|
|
666
|
+
out.set(ip, at + 1);
|
|
667
|
+
view.setUint16(at + 1 + ip.byteLength, port);
|
|
668
|
+
at += 1 + ip.byteLength + 2;
|
|
669
|
+
} else {
|
|
670
|
+
out[at] = 2;
|
|
671
|
+
at += 1;
|
|
672
|
+
}
|
|
673
|
+
view.setUint32(at, packet.data.byteLength);
|
|
674
|
+
out.set(packet.data, at + 4);
|
|
675
|
+
return out;
|
|
676
|
+
};
|
|
677
|
+
var encodeUdpPacket = (packet) => put(packet, new Uint8Array(size(packet)), 0);
|
|
678
|
+
/** The packet behind the `u32` length a stream carries it with. */
|
|
679
|
+
var encodeFramedUdpPacket = (packet) => {
|
|
680
|
+
const length = size(packet);
|
|
681
|
+
const out = new Uint8Array(4 + length);
|
|
682
|
+
new DataView(out.buffer).setUint32(0, length);
|
|
683
|
+
return put(packet, out, 4);
|
|
684
|
+
};
|
|
685
|
+
/** Reads `bytes` as one whole packet. `data` is a view into `bytes`, not a copy. */
|
|
686
|
+
var decodeUdpPacket = (bytes) => {
|
|
687
|
+
const r = reader(bytes);
|
|
688
|
+
const socket = r.u32();
|
|
689
|
+
const remote = r.optionalAddress();
|
|
690
|
+
const length = r.u32();
|
|
691
|
+
if (length > 65536) throw new ProtocolError("a length is over the limit");
|
|
692
|
+
return {
|
|
693
|
+
socket,
|
|
694
|
+
remote,
|
|
695
|
+
data: r.take(length)
|
|
696
|
+
};
|
|
697
|
+
};
|
|
698
|
+
// src/address.ts
|
|
699
|
+
var parseV4 = (text) => {
|
|
700
|
+
const parts = text.split(".");
|
|
701
|
+
if (parts.length !== 4) return void 0;
|
|
702
|
+
const bytes = /* @__PURE__ */ new Uint8Array(4);
|
|
703
|
+
for (const [at, part] of parts.entries()) {
|
|
704
|
+
if (!/^(0|[1-9]\d{0,2})$/.test(part) || Number(part) > 255) return void 0;
|
|
705
|
+
bytes[at] = Number(part);
|
|
706
|
+
}
|
|
707
|
+
return bytes;
|
|
708
|
+
};
|
|
709
|
+
var parseGroups = (text, last) => {
|
|
710
|
+
if (!text) return [];
|
|
711
|
+
const groups = [];
|
|
712
|
+
const parts = text.split(":");
|
|
713
|
+
for (const [at, part] of parts.entries()) if (last && at === parts.length - 1 && part.includes(".")) {
|
|
714
|
+
const v4 = parseV4(part);
|
|
715
|
+
if (!v4) return void 0;
|
|
716
|
+
groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
|
|
717
|
+
} else if (/^[0-9a-f]{1,4}$/i.test(part)) groups.push(parseInt(part, 16));
|
|
718
|
+
else return;
|
|
719
|
+
return groups;
|
|
720
|
+
};
|
|
721
|
+
var parseV6 = (text) => {
|
|
722
|
+
const halves = text.split("::");
|
|
723
|
+
if (halves.length > 2) return void 0;
|
|
724
|
+
const head = parseGroups(halves[0], halves.length === 1);
|
|
725
|
+
const tail = halves.length === 2 ? parseGroups(halves[1], true) : [];
|
|
726
|
+
if (!head || !tail) return void 0;
|
|
727
|
+
const missing = 8 - head.length - tail.length;
|
|
728
|
+
if (halves.length === 1 ? missing !== 0 : missing < 1) return void 0;
|
|
729
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
730
|
+
const view = new DataView(bytes.buffer);
|
|
731
|
+
head.forEach((group, at) => view.setUint16(at * 2, group));
|
|
732
|
+
tail.forEach((group, at) => view.setUint16((8 - tail.length + at) * 2, group));
|
|
733
|
+
return bytes;
|
|
734
|
+
};
|
|
735
|
+
/**
|
|
736
|
+
* The bytes of an IPv4 address in dotted decimal (`192.0.2.7`, 4 bytes) or of an IPv6 address in RFC 4291 text
|
|
737
|
+
* (`2001:db8::7`, `::ffff:192.0.2.7`, 16 bytes), as an `Address` holds them. `undefined` for anything else: a name,
|
|
738
|
+
* brackets, a port, a zone (`%eth0`) or an IPv4 part with a leading zero.
|
|
739
|
+
*/
|
|
740
|
+
var parseIp = (text) => parseV4(text) ?? parseV6(text);
|
|
741
|
+
/**
|
|
742
|
+
* The text of an address's 4 or 16 bytes: dotted decimal for IPv4, and for IPv6 the RFC 5952 form, in lower case
|
|
743
|
+
* with the longest run of zero groups shortened to `::` and an IPv4-mapped address ending in dotted decimal.
|
|
744
|
+
* Throws `TypeError` for any other length.
|
|
745
|
+
*/
|
|
746
|
+
var formatIp = (ip) => {
|
|
747
|
+
if (ip.byteLength === 4) return ip.join(".");
|
|
748
|
+
if (ip.byteLength !== 16) throw new TypeError(`an address holds 4 or 16 bytes, not ${ip.byteLength}`);
|
|
749
|
+
const view = new DataView(ip.buffer, ip.byteOffset, 16);
|
|
750
|
+
const groups = Array.from({ length: 8 }, (_, at) => view.getUint16(at * 2));
|
|
751
|
+
if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535) return `::ffff:${ip.subarray(12).join(".")}`;
|
|
752
|
+
let [start, length] = [-1, 1];
|
|
753
|
+
for (let at = 0; at < 8; at++) {
|
|
754
|
+
let end = at;
|
|
755
|
+
while (end < 8 && groups[end] === 0) end++;
|
|
756
|
+
if (end - at > length) [start, length] = [at, end - at];
|
|
757
|
+
}
|
|
758
|
+
const hex = (part) => part.map((group) => group.toString(16)).join(":");
|
|
759
|
+
if (start < 0) return hex(groups);
|
|
760
|
+
return `${hex(groups.slice(0, start))}::${hex(groups.slice(start + length))}`;
|
|
761
|
+
};
|
|
762
|
+
// src/context.ts
|
|
763
|
+
/**
|
|
764
|
+
* A request the relay refused, or one the client refused on its own: a feature the relay has off, no answer in
|
|
765
|
+
* time, a session that is closed. `code` is an `ErrorCode`; a code this package does not name is kept as the relay
|
|
766
|
+
* sent it and means `OTHER`. `message` is the relay's text for a person, or the client's. `closeCode` is the
|
|
767
|
+
* session's `CloseCode` when the session's end is why it failed, as for a `connect` that a full relay refused with
|
|
768
|
+
* `SESSION_LIMIT`, and absent otherwise.
|
|
769
|
+
*/
|
|
770
|
+
var WebVpnError = class extends Error {
|
|
771
|
+
code;
|
|
772
|
+
closeCode;
|
|
773
|
+
constructor(code, message, closeCode) {
|
|
774
|
+
super(message);
|
|
775
|
+
this.name = "WebVpnError";
|
|
776
|
+
this.code = code;
|
|
777
|
+
this.closeCode = closeCode;
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
/** The error of whatever a session's end made fail, with the session's `CloseCode` as its `closeCode`. */
|
|
781
|
+
var closeError = ({ code, reason }) => new WebVpnError(code === CloseCode.SESSION_LIMIT ? ErrorCode.CAPACITY : code === CloseCode.VERSION_MISMATCH ? ErrorCode.UNSUPPORTED : ErrorCode.OTHER, `the session closed: ${reason}`, code);
|
|
782
|
+
var EMPTY = /* @__PURE__ */ new Uint8Array(0);
|
|
783
|
+
var noop = () => {};
|
|
784
|
+
var concat = (first, second) => {
|
|
785
|
+
if (!first.byteLength) return second;
|
|
786
|
+
const both = new Uint8Array(first.byteLength + second.byteLength);
|
|
787
|
+
both.set(first);
|
|
788
|
+
both.set(second, first.byteLength);
|
|
789
|
+
return both;
|
|
790
|
+
};
|
|
791
|
+
var u32 = (value) => {
|
|
792
|
+
const bytes = /* @__PURE__ */ new Uint8Array(4);
|
|
793
|
+
new DataView(bytes.buffer).setUint32(0, value);
|
|
794
|
+
return bytes;
|
|
795
|
+
};
|
|
796
|
+
var readU32 = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0);
|
|
797
|
+
/** The code a stream's reset carried, as WebTransport and the mux both report it. */
|
|
798
|
+
var streamErrorCode = (error) => error?.streamErrorCode;
|
|
799
|
+
/** Rejects with a `WebVpnError` of `code` when `promise` takes longer than `ms`. */
|
|
800
|
+
var within = (promise, ms, code, message) => {
|
|
801
|
+
let timer;
|
|
802
|
+
const late = new Promise((_, reject) => {
|
|
803
|
+
timer = setTimeout(() => reject(new WebVpnError(code, message)), ms);
|
|
804
|
+
});
|
|
805
|
+
return Promise.race([promise, late]).finally(() => clearTimeout(timer));
|
|
806
|
+
};
|
|
807
|
+
var unexpected = (reply) => new WebVpnError(ErrorCode.OTHER, `the relay answered with ${reply.type}`);
|
|
808
|
+
var ok = (reply) => {
|
|
809
|
+
if (reply.type !== "ok") throw unexpected(reply);
|
|
810
|
+
};
|
|
811
|
+
/**
|
|
812
|
+
* Cuts a byte stream into frames. Each call takes the next chunk and returns the frames it completed, in order;
|
|
813
|
+
* `decode` returns `undefined` until the bytes hold a whole frame, so a frame split at any byte, in any number of
|
|
814
|
+
* chunks, comes out exactly once.
|
|
815
|
+
*/
|
|
816
|
+
var framed = (decode) => {
|
|
817
|
+
let held = EMPTY;
|
|
818
|
+
return (chunk) => {
|
|
819
|
+
let bytes = concat(held, chunk);
|
|
820
|
+
const frames = [];
|
|
821
|
+
for (let frame = decode(bytes); frame; frame = decode(bytes)) {
|
|
822
|
+
frames.push(frame);
|
|
823
|
+
bytes = bytes.subarray(frame.taken);
|
|
824
|
+
}
|
|
825
|
+
held = bytes.byteLength && bytes.buffer === chunk.buffer ? bytes.slice() : bytes;
|
|
826
|
+
return frames;
|
|
827
|
+
};
|
|
828
|
+
};
|
|
829
|
+
// src/dns.ts
|
|
830
|
+
var TYPES = {
|
|
831
|
+
A: 1,
|
|
832
|
+
AAAA: 28
|
|
833
|
+
};
|
|
834
|
+
var encoder = new TextEncoder();
|
|
835
|
+
/**
|
|
836
|
+
* A whole DNS message asking for the `A` or `AAAA` records of `name`, with recursion desired, as `Session.lookup`
|
|
837
|
+
* and a connect by name send it. The message id is 0, as RFC 8484 asks of a query that may reach a DNS over HTTPS
|
|
838
|
+
* resolver. The name goes as written, so a name outside ASCII must be given in its `xn--` form. Throws `TypeError`
|
|
839
|
+
* for a name DNS cannot carry: an empty label, a label over 63 bytes or a name over 253.
|
|
840
|
+
*/
|
|
841
|
+
var dnsQuery = (name, type = "A") => {
|
|
842
|
+
const labels = name.replace(/\.$/, "").split(".").map((label) => encoder.encode(label));
|
|
843
|
+
if (labels.some((label) => !label.byteLength || label.byteLength > 63) || name.replace(/\.$/, "").length > 253) throw new TypeError("the name is not one DNS can carry");
|
|
844
|
+
const length = labels.reduce((total, label) => total + 1 + label.byteLength, 1);
|
|
845
|
+
const message = new Uint8Array(12 + length + 4);
|
|
846
|
+
const view = new DataView(message.buffer);
|
|
847
|
+
view.setUint16(2, 256);
|
|
848
|
+
view.setUint16(4, 1);
|
|
849
|
+
let at = 12;
|
|
850
|
+
for (const label of labels) {
|
|
851
|
+
message[at] = label.byteLength;
|
|
852
|
+
message.set(label, at + 1);
|
|
853
|
+
at += 1 + label.byteLength;
|
|
854
|
+
}
|
|
855
|
+
view.setUint16(at + 1, TYPES[type]);
|
|
856
|
+
view.setUint16(at + 3, 1);
|
|
857
|
+
return message;
|
|
858
|
+
};
|
|
859
|
+
var pastName = (message, at) => {
|
|
860
|
+
while (at < message.byteLength) {
|
|
861
|
+
const length = message[at];
|
|
862
|
+
if (length === 0) return at + 1;
|
|
863
|
+
if (length >= 192) return at + 2;
|
|
864
|
+
at += 1 + length;
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
/**
|
|
868
|
+
* The addresses of the `A` and `AAAA` records in the answer section of a whole DNS message, as `Session.lookup`
|
|
869
|
+
* returns it, in the order the message gives them: 4 bytes for an `A` record, 16 for an `AAAA`. Other records, a
|
|
870
|
+
* `CNAME` among them, are skipped, and a message that ends early gives the records read before its end.
|
|
871
|
+
*/
|
|
872
|
+
var dnsAddresses = (message) => {
|
|
873
|
+
if (message.byteLength < 12) return [];
|
|
874
|
+
const view = new DataView(message.buffer, message.byteOffset, message.byteLength);
|
|
875
|
+
const addresses = [];
|
|
876
|
+
let at = 12;
|
|
877
|
+
for (let question = view.getUint16(4); question > 0 && at !== void 0; question--) {
|
|
878
|
+
at = pastName(message, at);
|
|
879
|
+
if (at !== void 0) at += 4;
|
|
880
|
+
}
|
|
881
|
+
for (let answer = view.getUint16(6); answer > 0 && at !== void 0; answer--) {
|
|
882
|
+
at = pastName(message, at);
|
|
883
|
+
if (at === void 0 || at + 10 > message.byteLength) break;
|
|
884
|
+
const [type, length] = [view.getUint16(at), view.getUint16(at + 8)];
|
|
885
|
+
const data = message.subarray(at + 10, at + 10 + length);
|
|
886
|
+
if (data.byteLength < length) break;
|
|
887
|
+
if (type === TYPES.A && length === 4 || type === TYPES.AAAA && length === 16) addresses.push(data.slice());
|
|
888
|
+
at += 10 + length;
|
|
889
|
+
}
|
|
890
|
+
return addresses;
|
|
891
|
+
};
|
|
892
|
+
// src/tcp.ts
|
|
893
|
+
var PEER_RESET_WAIT_MS = 1e3;
|
|
894
|
+
var peerReset = () => new WebVpnError(ErrorCode.CONNECTION_RESET, "the peer reset the connection");
|
|
895
|
+
var tcpSocket = (context, { socket, local, remote }, { head, reader, writable: upload }) => {
|
|
896
|
+
let closing = false;
|
|
897
|
+
let stopped = false;
|
|
898
|
+
let ending;
|
|
899
|
+
let downloadEnded;
|
|
900
|
+
const downloadEnd = new Promise((resolve) => {
|
|
901
|
+
downloadEnded = resolve;
|
|
902
|
+
});
|
|
903
|
+
reader.closed.then(() => downloadEnded(), downloadEnded);
|
|
904
|
+
let controller;
|
|
905
|
+
const readable = new ReadableStream({
|
|
906
|
+
start: (started) => {
|
|
907
|
+
controller = started;
|
|
908
|
+
},
|
|
909
|
+
pull: async () => {
|
|
910
|
+
if (head.byteLength) {
|
|
911
|
+
controller.enqueue(head);
|
|
912
|
+
head = EMPTY;
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
try {
|
|
916
|
+
const { value, done } = await reader.read();
|
|
917
|
+
if (stopped) return;
|
|
918
|
+
if (done) return controller.close();
|
|
919
|
+
controller.enqueue(value);
|
|
920
|
+
} catch (error) {
|
|
921
|
+
if (stopped) return;
|
|
922
|
+
const code = streamErrorCode(error);
|
|
923
|
+
if (code === ResetCode.PEER_RESET) return controller.error(peerReset());
|
|
924
|
+
if (closing || code === ResetCode.CLOSED) return controller.close();
|
|
925
|
+
controller.error(context.ended() ?? error);
|
|
926
|
+
}
|
|
927
|
+
},
|
|
928
|
+
cancel: (reason) => reader.cancel(reason)
|
|
929
|
+
}, { highWaterMark: 0 });
|
|
930
|
+
const stopReading = async () => {
|
|
931
|
+
if (stopped) return;
|
|
932
|
+
stopped = true;
|
|
933
|
+
try {
|
|
934
|
+
controller.close();
|
|
935
|
+
} catch {}
|
|
936
|
+
try {
|
|
937
|
+
while (!(await reader.read()).done);
|
|
938
|
+
} catch {}
|
|
939
|
+
};
|
|
940
|
+
const writer = upload.getWriter();
|
|
941
|
+
const failed = async (error) => {
|
|
942
|
+
let timer;
|
|
943
|
+
const end = await Promise.race([downloadEnd, new Promise((resolve) => {
|
|
944
|
+
timer = setTimeout(resolve, PEER_RESET_WAIT_MS);
|
|
945
|
+
})]);
|
|
946
|
+
clearTimeout(timer);
|
|
947
|
+
throw streamErrorCode(end) === ResetCode.PEER_RESET ? peerReset() : error;
|
|
948
|
+
};
|
|
949
|
+
const writable = new WritableStream({
|
|
950
|
+
write: (chunk) => writer.write(chunk).catch(failed),
|
|
951
|
+
close: () => writer.close().catch(failed),
|
|
952
|
+
abort: (reason) => writer.abort(reason)
|
|
953
|
+
});
|
|
954
|
+
const end = (type) => ending ??= (async () => {
|
|
955
|
+
closing = true;
|
|
956
|
+
if (context.ended()) return;
|
|
957
|
+
try {
|
|
958
|
+
await context.request({
|
|
959
|
+
type,
|
|
960
|
+
socket
|
|
961
|
+
}, ok);
|
|
962
|
+
} catch (error) {
|
|
963
|
+
if (!context.ended()) throw error;
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
stopReading();
|
|
967
|
+
})();
|
|
968
|
+
return {
|
|
969
|
+
id: socket,
|
|
970
|
+
local,
|
|
971
|
+
remote,
|
|
972
|
+
readable,
|
|
973
|
+
writable,
|
|
974
|
+
setOption: (option) => context.request({
|
|
975
|
+
type: "tcpSetOption",
|
|
976
|
+
socket,
|
|
977
|
+
option
|
|
978
|
+
}, ok),
|
|
979
|
+
close: () => end("tcpClose"),
|
|
980
|
+
reset: () => end("tcpReset")
|
|
981
|
+
};
|
|
982
|
+
};
|
|
983
|
+
// src/listener.ts
|
|
984
|
+
var ACCEPTED_STREAM_MS = 3e4;
|
|
985
|
+
var tcpListener = (context, { socket, local }) => {
|
|
986
|
+
let done = false;
|
|
987
|
+
let closing;
|
|
988
|
+
let finish;
|
|
989
|
+
const closed = new Promise((resolve) => {
|
|
990
|
+
finish = resolve;
|
|
991
|
+
});
|
|
992
|
+
const waiting = [];
|
|
993
|
+
let wake;
|
|
994
|
+
const connections = new ReadableStream({ pull: async (controller) => {
|
|
995
|
+
while (!waiting.length) {
|
|
996
|
+
if (done) return controller.close();
|
|
997
|
+
await new Promise((resolve) => {
|
|
998
|
+
wake = resolve;
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
controller.enqueue(waiting.shift());
|
|
1002
|
+
} }, { highWaterMark: 0 });
|
|
1003
|
+
const stop = (by) => {
|
|
1004
|
+
if (done) return;
|
|
1005
|
+
done = true;
|
|
1006
|
+
unown();
|
|
1007
|
+
context.retire(socket);
|
|
1008
|
+
for (const connection of waiting.splice(0)) connection.close().catch(noop);
|
|
1009
|
+
wake?.();
|
|
1010
|
+
finish(by);
|
|
1011
|
+
};
|
|
1012
|
+
const accept = async (accepted) => {
|
|
1013
|
+
try {
|
|
1014
|
+
const connection = tcpSocket(context, accepted, await context.claim(accepted.socket, ACCEPTED_STREAM_MS));
|
|
1015
|
+
if (done) return connection.close().catch(noop);
|
|
1016
|
+
waiting.push(connection);
|
|
1017
|
+
wake?.();
|
|
1018
|
+
} catch {
|
|
1019
|
+
context.release("tcp", accepted.socket);
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
const unown = context.own(socket, {
|
|
1023
|
+
notice: (packet) => {
|
|
1024
|
+
if (packet.type === "accepted") accept(packet);
|
|
1025
|
+
if (packet.type === "closed") stop({
|
|
1026
|
+
by: "relay",
|
|
1027
|
+
code: packet.code
|
|
1028
|
+
});
|
|
1029
|
+
},
|
|
1030
|
+
end: () => stop({ by: "session" })
|
|
1031
|
+
});
|
|
1032
|
+
return {
|
|
1033
|
+
id: socket,
|
|
1034
|
+
local,
|
|
1035
|
+
connections,
|
|
1036
|
+
closed,
|
|
1037
|
+
close: () => closing ??= (async () => {
|
|
1038
|
+
if (done) return;
|
|
1039
|
+
const unlisten = context.request({
|
|
1040
|
+
type: "tcpUnlisten",
|
|
1041
|
+
socket
|
|
1042
|
+
}, ok);
|
|
1043
|
+
stop({ by: "client" });
|
|
1044
|
+
try {
|
|
1045
|
+
await unlisten;
|
|
1046
|
+
} catch (error) {
|
|
1047
|
+
if (!context.ended()) throw error;
|
|
1048
|
+
}
|
|
1049
|
+
})()
|
|
1050
|
+
};
|
|
1051
|
+
};
|
|
1052
|
+
// src/udp.ts
|
|
1053
|
+
var SOCKET_UNREAD_BYTES = 4194304;
|
|
1054
|
+
var SESSION_UNREAD_BYTES = 33554432;
|
|
1055
|
+
var PACKET_COST_BYTES = 256;
|
|
1056
|
+
var UPLINK_QUEUED_BYTES = 262144;
|
|
1057
|
+
var UNI_FALLBACK_MS = 8e3;
|
|
1058
|
+
var MAX_FRAME_BYTES = 27 + MAX_UDP_PAYLOAD_BYTES;
|
|
1059
|
+
var decodeFramed = (bytes) => {
|
|
1060
|
+
if (bytes.byteLength < 4) return void 0;
|
|
1061
|
+
const length = readU32(bytes);
|
|
1062
|
+
if (length > MAX_FRAME_BYTES) throw new ProtocolError("a length is over the limit");
|
|
1063
|
+
if (bytes.byteLength < 4 + length) return void 0;
|
|
1064
|
+
let packet;
|
|
1065
|
+
try {
|
|
1066
|
+
packet = decodeUdpPacket(bytes.subarray(4, 4 + length));
|
|
1067
|
+
} catch {}
|
|
1068
|
+
return {
|
|
1069
|
+
packet,
|
|
1070
|
+
taken: 4 + length
|
|
1071
|
+
};
|
|
1072
|
+
};
|
|
1073
|
+
var udpSocket = (context, { socket, local }) => {
|
|
1074
|
+
let done = false;
|
|
1075
|
+
let closing;
|
|
1076
|
+
let finish;
|
|
1077
|
+
const closed = new Promise((resolve) => {
|
|
1078
|
+
finish = resolve;
|
|
1079
|
+
});
|
|
1080
|
+
const queue = [];
|
|
1081
|
+
let unread = 0;
|
|
1082
|
+
let wake;
|
|
1083
|
+
let uplink;
|
|
1084
|
+
let uplinkBytes = 0;
|
|
1085
|
+
const deliver = ({ remote, data }) => {
|
|
1086
|
+
const cost = PACKET_COST_BYTES + data.byteLength;
|
|
1087
|
+
if (done || !remote || unread + cost > SOCKET_UNREAD_BYTES) return;
|
|
1088
|
+
if (context.unread.bytes + cost > SESSION_UNREAD_BYTES) return;
|
|
1089
|
+
queue.push({
|
|
1090
|
+
remote,
|
|
1091
|
+
data: data.slice()
|
|
1092
|
+
});
|
|
1093
|
+
unread += cost;
|
|
1094
|
+
context.unread.bytes += cost;
|
|
1095
|
+
wake?.();
|
|
1096
|
+
};
|
|
1097
|
+
const drop = () => {
|
|
1098
|
+
context.unread.bytes -= unread;
|
|
1099
|
+
unread = 0;
|
|
1100
|
+
queue.length = 0;
|
|
1101
|
+
};
|
|
1102
|
+
const close = () => closing ??= (async () => {
|
|
1103
|
+
if (done) return;
|
|
1104
|
+
const asked = context.request({
|
|
1105
|
+
type: "udpClose",
|
|
1106
|
+
socket
|
|
1107
|
+
}, ok);
|
|
1108
|
+
stop({ by: "client" });
|
|
1109
|
+
try {
|
|
1110
|
+
await asked;
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
if (!context.ended()) throw error;
|
|
1113
|
+
}
|
|
1114
|
+
})();
|
|
1115
|
+
const readable = new ReadableStream({
|
|
1116
|
+
pull: async (controller) => {
|
|
1117
|
+
while (!queue.length) {
|
|
1118
|
+
if (done) return controller.close();
|
|
1119
|
+
await new Promise((resolve) => {
|
|
1120
|
+
wake = resolve;
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
const datagram = queue.shift();
|
|
1124
|
+
const cost = PACKET_COST_BYTES + datagram.data.byteLength;
|
|
1125
|
+
unread -= cost;
|
|
1126
|
+
context.unread.bytes -= cost;
|
|
1127
|
+
controller.enqueue(datagram);
|
|
1128
|
+
},
|
|
1129
|
+
cancel: () => close().catch(noop)
|
|
1130
|
+
}, { highWaterMark: 0 });
|
|
1131
|
+
const readStream = async ({ head, reader }) => {
|
|
1132
|
+
const take = framed(decodeFramed);
|
|
1133
|
+
try {
|
|
1134
|
+
for (let chunk = head;;) {
|
|
1135
|
+
for (const { packet } of take(chunk)) if (packet) deliver(packet);
|
|
1136
|
+
const { value, done: ended } = await reader.read();
|
|
1137
|
+
if (ended) return;
|
|
1138
|
+
chunk = value;
|
|
1139
|
+
}
|
|
1140
|
+
} catch {
|
|
1141
|
+
reader.cancel().catch(noop);
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
const useUplink = (writable) => {
|
|
1145
|
+
const writer = writable.getWriter();
|
|
1146
|
+
if (done || uplink) return writer.close().catch(noop);
|
|
1147
|
+
uplink = writer;
|
|
1148
|
+
writer.write(u32(socket)).catch(noop);
|
|
1149
|
+
};
|
|
1150
|
+
context.claim(socket).then((stream) => {
|
|
1151
|
+
readStream(stream);
|
|
1152
|
+
if (stream.writable) useUplink(stream.writable);
|
|
1153
|
+
}, noop);
|
|
1154
|
+
const { openUni } = context.carrier;
|
|
1155
|
+
const fallback = openUni && setTimeout(() => {
|
|
1156
|
+
if (!done && !uplink) openUni().then(useUplink, noop);
|
|
1157
|
+
}, UNI_FALLBACK_MS);
|
|
1158
|
+
const send = ({ remote, data }) => {
|
|
1159
|
+
const packet = {
|
|
1160
|
+
socket,
|
|
1161
|
+
remote,
|
|
1162
|
+
data
|
|
1163
|
+
};
|
|
1164
|
+
const writer = uplink;
|
|
1165
|
+
if (!writer) return context.carrier.sendDatagram(encodeUdpPacket(packet));
|
|
1166
|
+
const frame = encodeFramedUdpPacket(packet);
|
|
1167
|
+
if (uplinkBytes + frame.byteLength > UPLINK_QUEUED_BYTES) return;
|
|
1168
|
+
uplinkBytes += frame.byteLength;
|
|
1169
|
+
writer.write(frame).catch(() => {
|
|
1170
|
+
if (uplink === writer) uplink = void 0;
|
|
1171
|
+
}).finally(() => {
|
|
1172
|
+
uplinkBytes -= frame.byteLength;
|
|
1173
|
+
});
|
|
1174
|
+
};
|
|
1175
|
+
const writable = new WritableStream({ write: (datagram) => {
|
|
1176
|
+
if (done) throw context.ended() ?? new WebVpnError(ErrorCode.OTHER, "the socket is closed");
|
|
1177
|
+
if (datagram.data.byteLength > 65536) throw new WebVpnError(ErrorCode.OTHER, `the datagram is too large: a UDP payload holds at most ${MAX_UDP_PAYLOAD_BYTES} bytes`);
|
|
1178
|
+
send(datagram);
|
|
1179
|
+
} });
|
|
1180
|
+
const stop = (by) => {
|
|
1181
|
+
if (done) return;
|
|
1182
|
+
done = true;
|
|
1183
|
+
unown();
|
|
1184
|
+
clearTimeout(fallback);
|
|
1185
|
+
context.retire(socket);
|
|
1186
|
+
drop();
|
|
1187
|
+
wake?.();
|
|
1188
|
+
uplink?.close().catch(noop);
|
|
1189
|
+
finish(by);
|
|
1190
|
+
};
|
|
1191
|
+
const unown = context.own(socket, {
|
|
1192
|
+
notice: (packet) => {
|
|
1193
|
+
if (packet.type === "closed") stop({
|
|
1194
|
+
by: "relay",
|
|
1195
|
+
code: packet.code
|
|
1196
|
+
});
|
|
1197
|
+
},
|
|
1198
|
+
packet: deliver,
|
|
1199
|
+
end: () => stop({ by: "session" })
|
|
1200
|
+
});
|
|
1201
|
+
return {
|
|
1202
|
+
id: socket,
|
|
1203
|
+
local,
|
|
1204
|
+
readable,
|
|
1205
|
+
writable,
|
|
1206
|
+
connect: (remote) => context.request({
|
|
1207
|
+
type: "udpConnect",
|
|
1208
|
+
socket,
|
|
1209
|
+
remote
|
|
1210
|
+
}, ok),
|
|
1211
|
+
disconnect: () => context.request({
|
|
1212
|
+
type: "udpDisconnect",
|
|
1213
|
+
socket
|
|
1214
|
+
}, ok),
|
|
1215
|
+
setOption: (option) => context.request({
|
|
1216
|
+
type: "udpSetOption",
|
|
1217
|
+
socket,
|
|
1218
|
+
option
|
|
1219
|
+
}, ok),
|
|
1220
|
+
closed,
|
|
1221
|
+
close
|
|
1222
|
+
};
|
|
1223
|
+
};
|
|
1224
|
+
// src/session.ts
|
|
1225
|
+
var AGENT = "@webvpn/client";
|
|
1226
|
+
var REQUEST_TIMEOUT_MS = 1e4;
|
|
1227
|
+
var CONNECT_TIMEOUT_MS = 12e3;
|
|
1228
|
+
var SETUP_TIMEOUT_MS = 4e3;
|
|
1229
|
+
var UNCLAIMED_STREAM_MS = 3e4;
|
|
1230
|
+
var RETIRED_SOCKET_MS = 3e4;
|
|
1231
|
+
var RETIRED_SOCKET_MAX = 4096;
|
|
1232
|
+
var LATE_REPLY_MS = 6e4;
|
|
1233
|
+
var LATE_REPLY_MAX = 512;
|
|
1234
|
+
var FRAME_HEADER_BYTES = 5;
|
|
1235
|
+
var CLOSES = {
|
|
1236
|
+
tcp: "tcpClose",
|
|
1237
|
+
listener: "tcpUnlisten",
|
|
1238
|
+
udp: "udpClose"
|
|
1239
|
+
};
|
|
1240
|
+
var remember = (map, key, value, ms, max) => {
|
|
1241
|
+
map.delete(key);
|
|
1242
|
+
map.set(key, value);
|
|
1243
|
+
for (const [old, { at }] of map) {
|
|
1244
|
+
if (value.at - at <= ms && map.size <= max) break;
|
|
1245
|
+
map.delete(old);
|
|
1246
|
+
}
|
|
1247
|
+
};
|
|
1248
|
+
var opened = (reply) => {
|
|
1249
|
+
if (reply.type !== "socket") throw unexpected(reply);
|
|
1250
|
+
return reply;
|
|
1251
|
+
};
|
|
1252
|
+
var connected = (reply) => {
|
|
1253
|
+
const socket = opened(reply);
|
|
1254
|
+
if (!socket.remote) throw unexpected(reply);
|
|
1255
|
+
return {
|
|
1256
|
+
...socket,
|
|
1257
|
+
remote: socket.remote
|
|
1258
|
+
};
|
|
1259
|
+
};
|
|
1260
|
+
var dispose = ({ reader, writable }) => {
|
|
1261
|
+
reader.cancel().catch(noop);
|
|
1262
|
+
writable?.abort().catch(noop);
|
|
1263
|
+
};
|
|
1264
|
+
/**
|
|
1265
|
+
* Runs a session on `carrier`: reads the relay's hello from the first stream the relay opens, answers with the
|
|
1266
|
+
* client's, and serves requests from then on. Rejects, with the carrier closed, when the relay's version does not
|
|
1267
|
+
* suit (`VERSION_MISMATCH`), when the relay closes the session in its setup (the error's `closeCode` says why, as
|
|
1268
|
+
* `SESSION_LIMIT` for a full relay), when the setup breaks the protocol, ends, or does not finish within 4 seconds.
|
|
1269
|
+
*/
|
|
1270
|
+
var openSession = async (carrier, options = {}) => {
|
|
1271
|
+
let ended;
|
|
1272
|
+
let heard = false;
|
|
1273
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1274
|
+
const late = /* @__PURE__ */ new Map();
|
|
1275
|
+
const retired = /* @__PURE__ */ new Map();
|
|
1276
|
+
const parked = /* @__PURE__ */ new Map();
|
|
1277
|
+
const claims = /* @__PURE__ */ new Map();
|
|
1278
|
+
const owners = /* @__PURE__ */ new Map();
|
|
1279
|
+
let announceDraining;
|
|
1280
|
+
const draining = new Promise((resolve) => {
|
|
1281
|
+
announceDraining = resolve;
|
|
1282
|
+
});
|
|
1283
|
+
let lastId = 0;
|
|
1284
|
+
const end = (info) => {
|
|
1285
|
+
if (ended) return;
|
|
1286
|
+
ended = closeError(info);
|
|
1287
|
+
for (const { fail } of pending.values()) fail(ended);
|
|
1288
|
+
for (const { reject } of claims.values()) reject(ended);
|
|
1289
|
+
for (const { stream, timer } of parked.values()) {
|
|
1290
|
+
clearTimeout(timer);
|
|
1291
|
+
dispose(stream);
|
|
1292
|
+
}
|
|
1293
|
+
for (const owner of [...owners.values()]) owner.end();
|
|
1294
|
+
for (const map of [
|
|
1295
|
+
pending,
|
|
1296
|
+
claims,
|
|
1297
|
+
parked,
|
|
1298
|
+
owners,
|
|
1299
|
+
late,
|
|
1300
|
+
retired
|
|
1301
|
+
]) map.clear();
|
|
1302
|
+
};
|
|
1303
|
+
carrier.closed.then(end);
|
|
1304
|
+
const fail = (code, reason) => carrier.close(code, reason);
|
|
1305
|
+
const incoming = carrier.incoming.getReader();
|
|
1306
|
+
const setup = async () => {
|
|
1307
|
+
const { value: control } = await incoming.read();
|
|
1308
|
+
if (!control) throw new WebVpnError(ErrorCode.OTHER, "the relay opened no control stream");
|
|
1309
|
+
const reader = control.readable.getReader();
|
|
1310
|
+
const take = framed(decodeRelayPacket);
|
|
1311
|
+
const backlog = [];
|
|
1312
|
+
const next = async () => {
|
|
1313
|
+
while (!backlog.length) {
|
|
1314
|
+
const { value, done } = await reader.read();
|
|
1315
|
+
if (done) return void 0;
|
|
1316
|
+
backlog.push(...take(value).map(({ packet }) => packet));
|
|
1317
|
+
}
|
|
1318
|
+
return backlog.shift();
|
|
1319
|
+
};
|
|
1320
|
+
const relayHello = await next();
|
|
1321
|
+
if (relayHello?.type === "bye") {
|
|
1322
|
+
fail(relayHello.code, relayHello.reason);
|
|
1323
|
+
throw closeError(relayHello);
|
|
1324
|
+
}
|
|
1325
|
+
if (relayHello?.type !== "hello") throw new ProtocolError("the relay did not start with its hello");
|
|
1326
|
+
if (!compatible(relayHello)) {
|
|
1327
|
+
const reason = `the relay speaks WebVPN ${relayHello.major}.${relayHello.minor}`;
|
|
1328
|
+
fail(CloseCode.VERSION_MISMATCH, reason);
|
|
1329
|
+
throw closeError({
|
|
1330
|
+
code: CloseCode.VERSION_MISMATCH,
|
|
1331
|
+
reason
|
|
1332
|
+
});
|
|
1333
|
+
}
|
|
1334
|
+
const writer = control.writable.getWriter();
|
|
1335
|
+
await writer.write(encodeClientPacket(hello(0, options.agent ?? AGENT)));
|
|
1336
|
+
return {
|
|
1337
|
+
next,
|
|
1338
|
+
writer,
|
|
1339
|
+
features: relayHello.features
|
|
1340
|
+
};
|
|
1341
|
+
};
|
|
1342
|
+
const { next, writer, features } = await within(Promise.race([setup(), carrier.closed.then((info) => {
|
|
1343
|
+
throw closeError(info);
|
|
1344
|
+
})]), SETUP_TIMEOUT_MS, ErrorCode.TIMED_OUT, "the relay did not finish the session setup in time").catch((error) => {
|
|
1345
|
+
fail(CloseCode.PROTOCOL_ERROR, error instanceof Error ? error.message : "the session setup failed");
|
|
1346
|
+
throw error;
|
|
1347
|
+
});
|
|
1348
|
+
const nextId = () => {
|
|
1349
|
+
do
|
|
1350
|
+
lastId = lastId + 1 >>> 0;
|
|
1351
|
+
while (pending.has(lastId) || late.has(lastId));
|
|
1352
|
+
return lastId;
|
|
1353
|
+
};
|
|
1354
|
+
const request = (packet, take, { timeoutMs = REQUEST_TIMEOUT_MS, opens } = {}) => new Promise((resolve, reject) => {
|
|
1355
|
+
if (ended) return reject(ended);
|
|
1356
|
+
const id = nextId();
|
|
1357
|
+
const frame = encodeClientPacket({
|
|
1358
|
+
...packet,
|
|
1359
|
+
id
|
|
1360
|
+
});
|
|
1361
|
+
if (frame.byteLength - FRAME_HEADER_BYTES > 4096) return reject(new WebVpnError(ErrorCode.OTHER, `a request holds at most ${MAX_CLIENT_FRAME_BYTES} bytes`));
|
|
1362
|
+
const timer = setTimeout(() => {
|
|
1363
|
+
pending.delete(id);
|
|
1364
|
+
remember(late, id, {
|
|
1365
|
+
at: Date.now(),
|
|
1366
|
+
opens
|
|
1367
|
+
}, LATE_REPLY_MS, LATE_REPLY_MAX);
|
|
1368
|
+
if (!heard) fail(CloseCode.PROTOCOL_ERROR, "the relay answers nothing");
|
|
1369
|
+
reject(new WebVpnError(ErrorCode.TIMED_OUT, `the relay did not answer in ${timeoutMs} ms`));
|
|
1370
|
+
}, timeoutMs);
|
|
1371
|
+
pending.set(id, {
|
|
1372
|
+
settle: (reply) => {
|
|
1373
|
+
clearTimeout(timer);
|
|
1374
|
+
if (reply.type === "error") return reject(new WebVpnError(reply.code, reply.message));
|
|
1375
|
+
try {
|
|
1376
|
+
resolve(take(reply));
|
|
1377
|
+
} catch (error) {
|
|
1378
|
+
reject(error);
|
|
1379
|
+
}
|
|
1380
|
+
},
|
|
1381
|
+
fail: (error) => {
|
|
1382
|
+
clearTimeout(timer);
|
|
1383
|
+
reject(error);
|
|
1384
|
+
}
|
|
1385
|
+
});
|
|
1386
|
+
writer.write(frame).catch(() => fail(CloseCode.PROTOCOL_ERROR, "the control stream failed"));
|
|
1387
|
+
});
|
|
1388
|
+
const isRetired = (socket) => Date.now() - (retired.get(socket)?.at ?? -Infinity) <= RETIRED_SOCKET_MS;
|
|
1389
|
+
const retire = (socket) => {
|
|
1390
|
+
if (ended) return;
|
|
1391
|
+
const held = parked.get(socket);
|
|
1392
|
+
if (held) {
|
|
1393
|
+
clearTimeout(held.timer);
|
|
1394
|
+
dispose(held.stream);
|
|
1395
|
+
}
|
|
1396
|
+
claims.get(socket)?.reject(new WebVpnError(ErrorCode.OTHER, "the socket closed"));
|
|
1397
|
+
parked.delete(socket);
|
|
1398
|
+
claims.delete(socket);
|
|
1399
|
+
remember(retired, socket, { at: Date.now() }, RETIRED_SOCKET_MS, RETIRED_SOCKET_MAX);
|
|
1400
|
+
};
|
|
1401
|
+
const release = (opens, socket) => {
|
|
1402
|
+
retire(socket);
|
|
1403
|
+
request({
|
|
1404
|
+
type: CLOSES[opens],
|
|
1405
|
+
socket
|
|
1406
|
+
}, ok).catch(noop);
|
|
1407
|
+
};
|
|
1408
|
+
const claim = (socket, timeoutMs) => {
|
|
1409
|
+
if (ended) return Promise.reject(ended);
|
|
1410
|
+
const held = parked.get(socket);
|
|
1411
|
+
if (held) {
|
|
1412
|
+
clearTimeout(held.timer);
|
|
1413
|
+
parked.delete(socket);
|
|
1414
|
+
return Promise.resolve(held.stream);
|
|
1415
|
+
}
|
|
1416
|
+
const arrival = new Promise((resolve, reject) => claims.set(socket, {
|
|
1417
|
+
resolve,
|
|
1418
|
+
reject
|
|
1419
|
+
}));
|
|
1420
|
+
if (timeoutMs === void 0) return arrival;
|
|
1421
|
+
return within(arrival, timeoutMs, ErrorCode.NO_STREAM, "the relay did not open the socket's stream in time").catch((error) => {
|
|
1422
|
+
claims.delete(socket);
|
|
1423
|
+
throw error;
|
|
1424
|
+
});
|
|
1425
|
+
};
|
|
1426
|
+
const arrive = (socket, stream) => {
|
|
1427
|
+
if (ended || isRetired(socket)) return dispose(stream);
|
|
1428
|
+
const claimed = claims.get(socket);
|
|
1429
|
+
if (claimed) {
|
|
1430
|
+
claims.delete(socket);
|
|
1431
|
+
return claimed.resolve(stream);
|
|
1432
|
+
}
|
|
1433
|
+
const previous = parked.get(socket);
|
|
1434
|
+
if (previous) {
|
|
1435
|
+
clearTimeout(previous.timer);
|
|
1436
|
+
dispose(previous.stream);
|
|
1437
|
+
}
|
|
1438
|
+
const timer = setTimeout(() => {
|
|
1439
|
+
parked.delete(socket);
|
|
1440
|
+
dispose(stream);
|
|
1441
|
+
}, UNCLAIMED_STREAM_MS);
|
|
1442
|
+
parked.set(socket, {
|
|
1443
|
+
stream,
|
|
1444
|
+
timer
|
|
1445
|
+
});
|
|
1446
|
+
};
|
|
1447
|
+
const readId = async (readable, writable) => {
|
|
1448
|
+
const reader = readable.getReader();
|
|
1449
|
+
let head = EMPTY;
|
|
1450
|
+
try {
|
|
1451
|
+
while (head.byteLength < 4) {
|
|
1452
|
+
const { value, done } = await reader.read();
|
|
1453
|
+
if (done) return dispose({
|
|
1454
|
+
reader,
|
|
1455
|
+
writable
|
|
1456
|
+
});
|
|
1457
|
+
head = concat(head, value);
|
|
1458
|
+
}
|
|
1459
|
+
} catch {
|
|
1460
|
+
return dispose({
|
|
1461
|
+
reader,
|
|
1462
|
+
writable
|
|
1463
|
+
});
|
|
1464
|
+
}
|
|
1465
|
+
arrive(readU32(head), {
|
|
1466
|
+
head: head.subarray(4),
|
|
1467
|
+
reader,
|
|
1468
|
+
writable
|
|
1469
|
+
});
|
|
1470
|
+
};
|
|
1471
|
+
const acceptStreams = async (reader, accept) => {
|
|
1472
|
+
try {
|
|
1473
|
+
for (let read = await reader.read(); !read.done; read = await reader.read()) accept(read.value);
|
|
1474
|
+
} catch {}
|
|
1475
|
+
};
|
|
1476
|
+
acceptStreams(incoming, ({ readable, writable }) => readId(readable, writable));
|
|
1477
|
+
acceptStreams(carrier.incomingUni.getReader(), (readable) => readId(readable));
|
|
1478
|
+
if (carrier.datagrams) acceptStreams(carrier.datagrams.getReader(), (datagram) => {
|
|
1479
|
+
try {
|
|
1480
|
+
const packet = decodeUdpPacket(datagram);
|
|
1481
|
+
owners.get(packet.socket)?.packet?.(packet);
|
|
1482
|
+
} catch {}
|
|
1483
|
+
});
|
|
1484
|
+
const reply = (packet) => {
|
|
1485
|
+
const waiting = pending.get(packet.id);
|
|
1486
|
+
if (waiting) {
|
|
1487
|
+
pending.delete(packet.id);
|
|
1488
|
+
return waiting.settle(packet);
|
|
1489
|
+
}
|
|
1490
|
+
const given = late.get(packet.id);
|
|
1491
|
+
if (!given) return;
|
|
1492
|
+
late.delete(packet.id);
|
|
1493
|
+
if (packet.type === "socket" && given.opens) release(given.opens, packet.socket);
|
|
1494
|
+
};
|
|
1495
|
+
const notify = (socket, packet) => {
|
|
1496
|
+
const owner = owners.get(socket);
|
|
1497
|
+
if (owner) return owner.notice(packet);
|
|
1498
|
+
if (packet.type === "accepted") release("tcp", packet.socket);
|
|
1499
|
+
};
|
|
1500
|
+
const readControl = async () => {
|
|
1501
|
+
try {
|
|
1502
|
+
for (let packet = await next(); packet; packet = await next()) {
|
|
1503
|
+
heard = true;
|
|
1504
|
+
switch (packet.type) {
|
|
1505
|
+
case "ok":
|
|
1506
|
+
case "error":
|
|
1507
|
+
case "socket":
|
|
1508
|
+
case "dnsAnswer":
|
|
1509
|
+
reply(packet);
|
|
1510
|
+
break;
|
|
1511
|
+
case "accepted":
|
|
1512
|
+
case "acceptRefused":
|
|
1513
|
+
notify(packet.listener, packet);
|
|
1514
|
+
break;
|
|
1515
|
+
case "closed":
|
|
1516
|
+
notify(packet.socket, packet);
|
|
1517
|
+
break;
|
|
1518
|
+
case "draining":
|
|
1519
|
+
announceDraining();
|
|
1520
|
+
break;
|
|
1521
|
+
case "bye": return fail(packet.code, packet.reason);
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
fail(CloseCode.PROTOCOL_ERROR, "the relay ended the control stream");
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
fail(CloseCode.PROTOCOL_ERROR, error instanceof ProtocolError ? error.message : "the control stream failed");
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
readControl();
|
|
1530
|
+
const context = {
|
|
1531
|
+
carrier,
|
|
1532
|
+
request,
|
|
1533
|
+
claim,
|
|
1534
|
+
retire,
|
|
1535
|
+
release,
|
|
1536
|
+
own: (socket, owner) => {
|
|
1537
|
+
owners.set(socket, owner);
|
|
1538
|
+
return () => {
|
|
1539
|
+
if (owners.get(socket) === owner) owners.delete(socket);
|
|
1540
|
+
};
|
|
1541
|
+
},
|
|
1542
|
+
ended: () => ended,
|
|
1543
|
+
unread: { bytes: 0 }
|
|
1544
|
+
};
|
|
1545
|
+
const offered = (bit, what) => {
|
|
1546
|
+
if (!(features & bit)) throw new WebVpnError(ErrorCode.UNSUPPORTED, `the relay does not take ${what}`);
|
|
1547
|
+
};
|
|
1548
|
+
return {
|
|
1549
|
+
carrier: carrier.kind,
|
|
1550
|
+
features,
|
|
1551
|
+
closed: carrier.closed,
|
|
1552
|
+
draining,
|
|
1553
|
+
authenticate: async (credential) => {
|
|
1554
|
+
offered(Feature.AUTH, "credentials");
|
|
1555
|
+
await request({
|
|
1556
|
+
type: "auth",
|
|
1557
|
+
credential
|
|
1558
|
+
}, ok);
|
|
1559
|
+
},
|
|
1560
|
+
clearAuth: async () => {
|
|
1561
|
+
offered(Feature.AUTH, "credentials");
|
|
1562
|
+
await request({ type: "authClear" }, ok);
|
|
1563
|
+
},
|
|
1564
|
+
tcpConnect: async (target) => {
|
|
1565
|
+
let packet = {
|
|
1566
|
+
type: "tcpConnect",
|
|
1567
|
+
remote: target
|
|
1568
|
+
};
|
|
1569
|
+
if ("name" in target) {
|
|
1570
|
+
offered(Feature.DNS, "names");
|
|
1571
|
+
packet = {
|
|
1572
|
+
type: "tcpConnectName",
|
|
1573
|
+
port: target.port,
|
|
1574
|
+
query: dnsQuery(target.name, "A")
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
const socket = await request(packet, connected, {
|
|
1578
|
+
timeoutMs: CONNECT_TIMEOUT_MS,
|
|
1579
|
+
opens: "tcp"
|
|
1580
|
+
});
|
|
1581
|
+
const stream = await claim(socket.socket, UNCLAIMED_STREAM_MS).catch((error) => {
|
|
1582
|
+
release("tcp", socket.socket);
|
|
1583
|
+
throw error;
|
|
1584
|
+
});
|
|
1585
|
+
return tcpSocket(context, socket, stream);
|
|
1586
|
+
},
|
|
1587
|
+
tcpListen: async (local) => {
|
|
1588
|
+
offered(Feature.LISTEN, "listeners");
|
|
1589
|
+
return request({
|
|
1590
|
+
type: "tcpListen",
|
|
1591
|
+
local
|
|
1592
|
+
}, (reply) => tcpListener(context, opened(reply)), { opens: "listener" });
|
|
1593
|
+
},
|
|
1594
|
+
udpBind: (local) => request({
|
|
1595
|
+
type: "udpBind",
|
|
1596
|
+
local
|
|
1597
|
+
}, (reply) => udpSocket(context, opened(reply)), { opens: "udp" }),
|
|
1598
|
+
lookup: async (query) => {
|
|
1599
|
+
offered(Feature.DNS, "names");
|
|
1600
|
+
return request({
|
|
1601
|
+
type: "dnsQuery",
|
|
1602
|
+
query
|
|
1603
|
+
}, (reply) => {
|
|
1604
|
+
if (reply.type !== "dnsAnswer") throw unexpected(reply);
|
|
1605
|
+
return reply.answer;
|
|
1606
|
+
});
|
|
1607
|
+
},
|
|
1608
|
+
close: () => fail(CloseCode.NORMAL, "the client closed the session")
|
|
1609
|
+
};
|
|
1610
|
+
};
|
|
1611
|
+
// src/websocket.ts
|
|
1612
|
+
var OPEN_TIMEOUT_MS = 6e3;
|
|
1613
|
+
var MAX_DATA_BYTES = 262144;
|
|
1614
|
+
var SOCKET_BUFFER_TARGET = 1048576;
|
|
1615
|
+
var DATAGRAM_SHED_BYTES = 2097152;
|
|
1616
|
+
var POLL_MIN_MS = 5;
|
|
1617
|
+
var POLL_MAX_MS = 40;
|
|
1618
|
+
var STREAM_WINDOW_BYTES = 1048576;
|
|
1619
|
+
var OPEN = 1;
|
|
1620
|
+
/** The session's `CloseCode` a WebSocket close carries, and `LOST` for a close with none of the relay's codes. */
|
|
1621
|
+
var closeInfo = ({ code, reason }) => ({
|
|
1622
|
+
code: code >= 4e3 && code < 5e3 ? code - 4e3 : CloseCode.LOST,
|
|
1623
|
+
reason
|
|
1624
|
+
});
|
|
1625
|
+
/**
|
|
1626
|
+
* The carrier of a WebSocket session: the mux of `spec/protocol.md` over `socket`, which the caller made just before.
|
|
1627
|
+
* Rejects, with the socket closed, when it does not open in 6 seconds, or when it closes before it opened: with the
|
|
1628
|
+
* session's end as the error when that close carries one of the relay's codes.
|
|
1629
|
+
*/
|
|
1630
|
+
var webSocketCarrier = async (socket) => {
|
|
1631
|
+
socket.binaryType = "arraybuffer";
|
|
1632
|
+
const streams = /* @__PURE__ */ new Map();
|
|
1633
|
+
let incoming;
|
|
1634
|
+
let incomingUni;
|
|
1635
|
+
let control;
|
|
1636
|
+
const send = (kind, stream, payload) => {
|
|
1637
|
+
if (socket.readyState === OPEN) socket.send(encodeMuxFrame(kind, stream, payload));
|
|
1638
|
+
};
|
|
1639
|
+
const ready = [];
|
|
1640
|
+
let timer;
|
|
1641
|
+
let poll = POLL_MIN_MS;
|
|
1642
|
+
const pump = () => {
|
|
1643
|
+
timer = void 0;
|
|
1644
|
+
let moved = false;
|
|
1645
|
+
while (ready.length && socket.readyState === OPEN && socket.bufferedAmount < SOCKET_BUFFER_TARGET) {
|
|
1646
|
+
const stream = ready.shift();
|
|
1647
|
+
const head = stream.sends[0];
|
|
1648
|
+
const end = Math.min(head.at + MAX_DATA_BYTES, head.chunk.byteLength);
|
|
1649
|
+
send(MuxKind.DATA, stream.id, head.chunk.subarray(head.at, end));
|
|
1650
|
+
head.at = end;
|
|
1651
|
+
moved = true;
|
|
1652
|
+
if (end === head.chunk.byteLength) {
|
|
1653
|
+
stream.sends.shift();
|
|
1654
|
+
head.resolve();
|
|
1655
|
+
}
|
|
1656
|
+
if (stream.sends.length) ready.push(stream);
|
|
1657
|
+
}
|
|
1658
|
+
if (!ready.length || socket.readyState !== OPEN) {
|
|
1659
|
+
poll = POLL_MIN_MS;
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
poll = moved ? POLL_MIN_MS : Math.min(poll * 2, POLL_MAX_MS);
|
|
1663
|
+
timer = setTimeout(pump, poll);
|
|
1664
|
+
};
|
|
1665
|
+
const write = (stream, chunk) => new Promise((resolve, reject) => {
|
|
1666
|
+
if (stream.failure) return reject(stream.failure);
|
|
1667
|
+
if (!chunk.byteLength) return resolve();
|
|
1668
|
+
stream.sends.push({
|
|
1669
|
+
chunk,
|
|
1670
|
+
at: 0,
|
|
1671
|
+
resolve,
|
|
1672
|
+
reject
|
|
1673
|
+
});
|
|
1674
|
+
if (stream.sends.length === 1) ready.push(stream);
|
|
1675
|
+
if (timer !== void 0 && socket.bufferedAmount >= SOCKET_BUFFER_TARGET) return;
|
|
1676
|
+
clearTimeout(timer);
|
|
1677
|
+
pump();
|
|
1678
|
+
});
|
|
1679
|
+
const forget = (stream) => {
|
|
1680
|
+
if (stream.finished && stream.sent && streams.get(stream.id) === stream) streams.delete(stream.id);
|
|
1681
|
+
};
|
|
1682
|
+
const terminate = (stream, failure, tellRelay) => {
|
|
1683
|
+
if (stream.failure) return;
|
|
1684
|
+
stream.failure = failure;
|
|
1685
|
+
if (tellRelay) stream.chunks.length = 0;
|
|
1686
|
+
if (streams.get(stream.id) === stream) streams.delete(stream.id);
|
|
1687
|
+
const at = ready.indexOf(stream);
|
|
1688
|
+
if (at >= 0) ready.splice(at, 1);
|
|
1689
|
+
for (const waiting of stream.sends.splice(0)) waiting.reject(failure);
|
|
1690
|
+
try {
|
|
1691
|
+
stream.writable?.error(failure);
|
|
1692
|
+
} catch {}
|
|
1693
|
+
stream.wake?.();
|
|
1694
|
+
if (tellRelay) send(MuxKind.RESET, stream.id);
|
|
1695
|
+
};
|
|
1696
|
+
const open = (id, both) => {
|
|
1697
|
+
const stream = {
|
|
1698
|
+
id,
|
|
1699
|
+
chunks: [],
|
|
1700
|
+
unread: 0,
|
|
1701
|
+
finished: false,
|
|
1702
|
+
sent: !both,
|
|
1703
|
+
sends: []
|
|
1704
|
+
};
|
|
1705
|
+
streams.set(id, stream);
|
|
1706
|
+
const readable = new ReadableStream({
|
|
1707
|
+
pull: async (controller) => {
|
|
1708
|
+
while (!stream.chunks.length) {
|
|
1709
|
+
if (stream.failure) throw stream.failure;
|
|
1710
|
+
if (stream.finished) return controller.close();
|
|
1711
|
+
await new Promise((resolve) => {
|
|
1712
|
+
stream.wake = resolve;
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
const chunk = stream.chunks.shift();
|
|
1716
|
+
stream.unread -= chunk.byteLength;
|
|
1717
|
+
controller.enqueue(chunk);
|
|
1718
|
+
send(MuxKind.CREDIT, id, u32(chunk.byteLength));
|
|
1719
|
+
},
|
|
1720
|
+
cancel: () => terminate(stream, /* @__PURE__ */ new Error("the stream was cancelled"), true)
|
|
1721
|
+
}, { highWaterMark: 0 });
|
|
1722
|
+
if (!both) return incomingUni.enqueue(readable);
|
|
1723
|
+
const writable = new WritableStream({
|
|
1724
|
+
start: (controller) => {
|
|
1725
|
+
stream.writable = controller;
|
|
1726
|
+
},
|
|
1727
|
+
write: (chunk) => write(stream, chunk),
|
|
1728
|
+
close: () => {
|
|
1729
|
+
stream.sent = true;
|
|
1730
|
+
send(MuxKind.FIN, id);
|
|
1731
|
+
forget(stream);
|
|
1732
|
+
},
|
|
1733
|
+
abort: () => terminate(stream, /* @__PURE__ */ new Error("the stream was aborted"), true)
|
|
1734
|
+
});
|
|
1735
|
+
incoming.enqueue({
|
|
1736
|
+
readable,
|
|
1737
|
+
writable
|
|
1738
|
+
});
|
|
1739
|
+
};
|
|
1740
|
+
const receive = (message) => {
|
|
1741
|
+
const frame = decodeMuxFrame(message);
|
|
1742
|
+
if (!frame) return;
|
|
1743
|
+
const { kind, stream: id, payload } = frame;
|
|
1744
|
+
if (kind === MuxKind.OPEN) {
|
|
1745
|
+
if (id === 0 || streams.has(id)) return;
|
|
1746
|
+
if (payload[0] === MuxStreamType.TCP) open(id, true);
|
|
1747
|
+
else if (payload[0] === MuxStreamType.UDP_DOWNLOAD) open(id, false);
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
if (kind === MuxKind.DATA && id === 0) return control.enqueue(payload);
|
|
1751
|
+
const stream = streams.get(id);
|
|
1752
|
+
if (!stream) return;
|
|
1753
|
+
if (kind === MuxKind.DATA && payload.byteLength && !stream.finished) {
|
|
1754
|
+
stream.unread += payload.byteLength;
|
|
1755
|
+
if (stream.unread > STREAM_WINDOW_BYTES) return terminate(stream, /* @__PURE__ */ new Error("the relay sent past the window"), true);
|
|
1756
|
+
stream.chunks.push(payload);
|
|
1757
|
+
stream.wake?.();
|
|
1758
|
+
} else if (kind === MuxKind.FIN) {
|
|
1759
|
+
stream.finished = true;
|
|
1760
|
+
stream.wake?.();
|
|
1761
|
+
forget(stream);
|
|
1762
|
+
} else if (kind === MuxKind.RESET) {
|
|
1763
|
+
const streamErrorCode = payload.byteLength >= 4 ? readU32(payload) : void 0;
|
|
1764
|
+
terminate(stream, Object.assign(/* @__PURE__ */ new Error("the relay reset the stream"), { streamErrorCode }), false);
|
|
1765
|
+
}
|
|
1766
|
+
};
|
|
1767
|
+
let settle;
|
|
1768
|
+
const closed = new Promise((resolve) => {
|
|
1769
|
+
settle = resolve;
|
|
1770
|
+
});
|
|
1771
|
+
const close = (code, reason) => {
|
|
1772
|
+
settle({
|
|
1773
|
+
code,
|
|
1774
|
+
reason
|
|
1775
|
+
});
|
|
1776
|
+
try {
|
|
1777
|
+
socket.close(4e3 + code, reason.slice(0, 123));
|
|
1778
|
+
} catch {}
|
|
1779
|
+
};
|
|
1780
|
+
socket.onmessage = (event) => {
|
|
1781
|
+
if (event.data instanceof ArrayBuffer) receive(new Uint8Array(event.data));
|
|
1782
|
+
};
|
|
1783
|
+
socket.onclose = (event) => {
|
|
1784
|
+
settle(closeInfo(event));
|
|
1785
|
+
clearTimeout(timer);
|
|
1786
|
+
const failure = /* @__PURE__ */ new Error("the WebSocket closed");
|
|
1787
|
+
for (const stream of [...streams.values()]) terminate(stream, failure, false);
|
|
1788
|
+
for (const controller of [
|
|
1789
|
+
control,
|
|
1790
|
+
incoming,
|
|
1791
|
+
incomingUni
|
|
1792
|
+
]) try {
|
|
1793
|
+
controller.close();
|
|
1794
|
+
} catch {}
|
|
1795
|
+
};
|
|
1796
|
+
const controlStream = {
|
|
1797
|
+
readable: new ReadableStream({ start: (controller) => {
|
|
1798
|
+
control = controller;
|
|
1799
|
+
} }),
|
|
1800
|
+
writable: new WritableStream({ write: (chunk) => {
|
|
1801
|
+
if (socket.readyState !== OPEN) throw new WebVpnError(ErrorCode.OTHER, "the WebSocket is closed");
|
|
1802
|
+
send(MuxKind.DATA, 0, chunk);
|
|
1803
|
+
} })
|
|
1804
|
+
};
|
|
1805
|
+
const carrier = {
|
|
1806
|
+
kind: "websocket",
|
|
1807
|
+
incoming: new ReadableStream({ start: (controller) => {
|
|
1808
|
+
incoming = controller;
|
|
1809
|
+
controller.enqueue(controlStream);
|
|
1810
|
+
} }),
|
|
1811
|
+
incomingUni: new ReadableStream({ start: (controller) => {
|
|
1812
|
+
incomingUni = controller;
|
|
1813
|
+
} }),
|
|
1814
|
+
sendDatagram: (packet) => {
|
|
1815
|
+
if (socket.bufferedAmount <= DATAGRAM_SHED_BYTES) send(MuxKind.DATAGRAM, 0, packet);
|
|
1816
|
+
},
|
|
1817
|
+
closed,
|
|
1818
|
+
close
|
|
1819
|
+
};
|
|
1820
|
+
await within(new Promise((resolve, reject) => {
|
|
1821
|
+
if (socket.readyState === OPEN) return resolve();
|
|
1822
|
+
socket.addEventListener("open", () => resolve(), { once: true });
|
|
1823
|
+
socket.addEventListener("close", (event) => {
|
|
1824
|
+
const info = closeInfo(event);
|
|
1825
|
+
reject(info.code === CloseCode.LOST ? new WebVpnError(ErrorCode.OTHER, "the WebSocket did not open") : closeError(info));
|
|
1826
|
+
}, { once: true });
|
|
1827
|
+
}), OPEN_TIMEOUT_MS, ErrorCode.TIMED_OUT, `the WebSocket did not open in ${OPEN_TIMEOUT_MS} ms`).catch((error) => {
|
|
1828
|
+
close(CloseCode.PROTOCOL_ERROR, "the session did not open");
|
|
1829
|
+
throw error;
|
|
1830
|
+
});
|
|
1831
|
+
return carrier;
|
|
1832
|
+
};
|
|
1833
|
+
// src/webtransport.ts
|
|
1834
|
+
var OUTGOING_DATAGRAMS = 256;
|
|
1835
|
+
var DATAGRAM_MAX_AGE_MS = 600;
|
|
1836
|
+
/**
|
|
1837
|
+
* The carrier of a WebTransport session, `transport` made by the caller just before: its first incoming stream must
|
|
1838
|
+
* be read before anything is awaited. Rejects, with the transport closed, when it is not ready in `readyTimeoutMs`.
|
|
1839
|
+
*/
|
|
1840
|
+
var webTransportCarrier = async (transport, readyTimeoutMs) => {
|
|
1841
|
+
const bidi = transport.incomingBidirectionalStreams.getReader();
|
|
1842
|
+
let first = bidi.read();
|
|
1843
|
+
first.catch(noop);
|
|
1844
|
+
let settle;
|
|
1845
|
+
const closed = new Promise((resolve) => {
|
|
1846
|
+
settle = resolve;
|
|
1847
|
+
});
|
|
1848
|
+
transport.closed.then((info) => settle({
|
|
1849
|
+
code: info.closeCode ?? CloseCode.LOST,
|
|
1850
|
+
reason: info.reason ?? ""
|
|
1851
|
+
}), (error) => settle({
|
|
1852
|
+
code: CloseCode.LOST,
|
|
1853
|
+
reason: error instanceof Error ? error.message : ""
|
|
1854
|
+
}));
|
|
1855
|
+
const close = (code, reason) => {
|
|
1856
|
+
settle({
|
|
1857
|
+
code,
|
|
1858
|
+
reason
|
|
1859
|
+
});
|
|
1860
|
+
try {
|
|
1861
|
+
transport.close({
|
|
1862
|
+
closeCode: code,
|
|
1863
|
+
reason
|
|
1864
|
+
});
|
|
1865
|
+
} catch {}
|
|
1866
|
+
};
|
|
1867
|
+
const message = `WebTransport was not ready in ${readyTimeoutMs} ms`;
|
|
1868
|
+
await within(transport.ready, readyTimeoutMs, ErrorCode.TIMED_OUT, message).catch((error) => {
|
|
1869
|
+
close(CloseCode.PROTOCOL_ERROR, "the session did not open");
|
|
1870
|
+
throw error;
|
|
1871
|
+
});
|
|
1872
|
+
try {
|
|
1873
|
+
transport.datagrams.outgoingMaxAge = DATAGRAM_MAX_AGE_MS;
|
|
1874
|
+
setOutgoingMaxBufferedDatagrams(transport.datagrams, OUTGOING_DATAGRAMS);
|
|
1875
|
+
} catch {}
|
|
1876
|
+
const datagrams = createWritable(transport.datagrams).getWriter();
|
|
1877
|
+
return {
|
|
1878
|
+
kind: "webtransport",
|
|
1879
|
+
incoming: new ReadableStream({
|
|
1880
|
+
pull: async (controller) => {
|
|
1881
|
+
const { value, done } = await (first ?? bidi.read());
|
|
1882
|
+
first = void 0;
|
|
1883
|
+
if (done) controller.close();
|
|
1884
|
+
else controller.enqueue(value);
|
|
1885
|
+
},
|
|
1886
|
+
cancel: (reason) => bidi.cancel(reason)
|
|
1887
|
+
}, { highWaterMark: 0 }),
|
|
1888
|
+
incomingUni: transport.incomingUnidirectionalStreams,
|
|
1889
|
+
datagrams: transport.datagrams.readable,
|
|
1890
|
+
sendDatagram: (packet) => {
|
|
1891
|
+
if ((datagrams.desiredSize ?? 0) > -4096) datagrams.write(packet).catch(noop);
|
|
1892
|
+
},
|
|
1893
|
+
openUni: () => transport.createUnidirectionalStream(),
|
|
1894
|
+
closed,
|
|
1895
|
+
close
|
|
1896
|
+
};
|
|
1897
|
+
};
|
|
1898
|
+
// src/connect.ts
|
|
1899
|
+
var WEBTRANSPORT_TIMEOUT_MS = 4e3;
|
|
1900
|
+
/**
|
|
1901
|
+
* Opens a session with a relay. Rejects with `TypeError` when the options name no URL for the carrier to take, and
|
|
1902
|
+
* otherwise with the last carrier's failure: a `WebVpnError` (the relay closed or refused the session, a version
|
|
1903
|
+
* that does not suit, a refused credential, a setup that took too long) or the browser's own error. A `WebVpnError`
|
|
1904
|
+
* the relay's close caused carries its `closeCode`, so a full relay (`SESSION_LIMIT`) or one that is stopping
|
|
1905
|
+
* (`RESTARTING`) reads apart from one that could not be reached.
|
|
1906
|
+
*/
|
|
1907
|
+
var connect = async (options) => {
|
|
1908
|
+
const { url, webSocketUrl, transport = "auto", agent } = options;
|
|
1909
|
+
let session;
|
|
1910
|
+
if (transport === "webtransport" || transport === "auto" && url && typeof WebTransport === "function") {
|
|
1911
|
+
if (!url) throw new TypeError("WebTransport needs `url`");
|
|
1912
|
+
try {
|
|
1913
|
+
const { serverCertificateHashes, webTransportTimeoutMs = WEBTRANSPORT_TIMEOUT_MS } = options;
|
|
1914
|
+
session = await openSession(await webTransportCarrier(new WebTransport(url, {
|
|
1915
|
+
congestionControl: "throughput",
|
|
1916
|
+
serverCertificateHashes
|
|
1917
|
+
}), webTransportTimeoutMs), { agent });
|
|
1918
|
+
} catch (error) {
|
|
1919
|
+
if (transport === "webtransport" || !webSocketUrl) throw error;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
if (!session) {
|
|
1923
|
+
if (!webSocketUrl) throw new TypeError("the WebSocket needs `webSocketUrl`");
|
|
1924
|
+
session = await openSession(await webSocketCarrier(new WebSocket(webSocketUrl)), { agent });
|
|
1925
|
+
}
|
|
1926
|
+
if (options.credential) {
|
|
1927
|
+
const opened = session;
|
|
1928
|
+
await opened.authenticate(options.credential).catch((error) => {
|
|
1929
|
+
opened.close();
|
|
1930
|
+
throw error;
|
|
1931
|
+
});
|
|
1932
|
+
}
|
|
1933
|
+
return session;
|
|
1934
|
+
};
|
|
1935
|
+
export { CONTROL_STREAM, CloseCode, ErrorCode, Feature, MAX_AGENT_BYTES, MAX_CLIENT_FRAME_BYTES, MAX_RELAY_FRAME_BYTES, MAX_UDP_PAYLOAD_BYTES, MuxKind, MuxStreamType, ProtocolError, ResetCode, VERSION, WebVpnError, compatible, connect, decodeClientPacket, decodeMuxFrame, decodeRelayPacket, decodeUdpPacket, dnsAddresses, dnsQuery, encodeClientPacket, encodeFramedUdpPacket, encodeMuxFrame, encodeRelayPacket, encodeUdpPacket, formatIp, hello, parseIp, websocketCloseCode };
|