@intellectual-frontiers/net 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/acme.d.ts +71 -0
- package/dist/acme.js +475 -0
- package/dist/dns.d.ts +57 -0
- package/dist/dns.js +381 -0
- package/dist/http-client.d.ts +149 -0
- package/dist/http-client.js +248 -0
- package/dist/mod.d.ts +21 -0
- package/dist/mod.js +21 -0
- package/dist/net.d.ts +84 -0
- package/dist/net.js +288 -0
- package/dist/serve.d.ts +33 -0
- package/dist/serve.js +109 -0
- package/dist/tcp.d.ts +77 -0
- package/dist/tcp.js +274 -0
- package/package.json +72 -4
- package/src/acme.ts +546 -0
- package/src/dns.ts +423 -0
- package/src/http-client.ts +369 -0
- package/src/mod.ts +22 -0
- package/src/net.ts +332 -0
- package/src/serve.ts +135 -0
- package/src/tcp.ts +344 -0
package/src/tcp.ts
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
// Spec: 0001-net FR-006
|
|
2
|
+
/**
|
|
3
|
+
* TCP connections, plain and over TLS (commons 0001-net FR-006), on `node:net` and `node:tls`: `listen`,
|
|
4
|
+
* `listenTls`, `connect` and `connectTls`. A {@link Listener} gives its
|
|
5
|
+
* address and its connections as an async iterable and closes by `close()`, an abort signal or `using`; a {@link Conn} gives its local and
|
|
6
|
+
* remote addresses, a web `ReadableStream` and `WritableStream` (made here by hand over the socket, the same on Bun and Node),
|
|
7
|
+
* `closeWrite` and `close`. Failures are thrown as the runtime's errors (FR-019): `AddrInUse`, `ConnectionRefused`, `TimedOut`
|
|
8
|
+
* (an `AbortSignal.timeout` that fired), and `InvalidData` for a server certificate that does not check out.
|
|
9
|
+
*
|
|
10
|
+
* Some choices are deliberate: `listen` and `listenTls` return a promise (Node binds asynchronously and reports a taken port
|
|
11
|
+
* then); a listener binds `127.0.0.1` unless asked, as `serve.ts` does, never every interface; `connectTls`'s `caCerts` replace the system's
|
|
12
|
+
* roots instead of adding to them, so a test or a pinned service trusts exactly the roots it names; and a TLS connection is given once its
|
|
13
|
+
* handshake is done.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { connect, listen } from "./tcp.ts";
|
|
18
|
+
* await using listener = await listen({ port: 0 });
|
|
19
|
+
* void (async () => {
|
|
20
|
+
* for await (const conn of listener) void conn.readable.pipeTo(conn.writable); // an echo server
|
|
21
|
+
* })();
|
|
22
|
+
* using conn = await connect({ port: listener.addr.port });
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @module
|
|
26
|
+
*/
|
|
27
|
+
import * as net from "node:net";
|
|
28
|
+
import * as tls from "node:tls";
|
|
29
|
+
import { ConnectionAborted, InvalidData, mapError, TimedOut, toError } from "@intellectual-frontiers/system/errors";
|
|
30
|
+
import type { NetAddr } from "./serve.ts";
|
|
31
|
+
|
|
32
|
+
export type { NetAddr } from "./serve.ts";
|
|
33
|
+
|
|
34
|
+
/** Where to listen. */
|
|
35
|
+
export type ListenOptions = {
|
|
36
|
+
/** The port; 0 (the default) asks the system for a free one. */
|
|
37
|
+
readonly port?: number;
|
|
38
|
+
/** The address to bind; `127.0.0.1` by default, never every interface unless asked (`0.0.0.0`, `::`). */
|
|
39
|
+
readonly hostname?: string;
|
|
40
|
+
/** Aborting it closes the listener. */
|
|
41
|
+
readonly signal?: AbortSignal;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** Where to listen for TLS, and the certificate to answer with. */
|
|
45
|
+
export type ListenTlsOptions = ListenOptions & {
|
|
46
|
+
/** The server's certificate chain, in PEM. */
|
|
47
|
+
readonly cert: string;
|
|
48
|
+
/** The certificate's private key, in PEM. */
|
|
49
|
+
readonly key: string;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** Where to connect. */
|
|
53
|
+
export type ConnectOptions = {
|
|
54
|
+
/** The host's name or address; `127.0.0.1` by default. */
|
|
55
|
+
readonly hostname?: string;
|
|
56
|
+
/** The port. */
|
|
57
|
+
readonly port: number;
|
|
58
|
+
/** Aborting it gives up while connecting (`TimedOut` where it is an `AbortSignal.timeout`); a connection made is not affected. */
|
|
59
|
+
readonly signal?: AbortSignal;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** Where to connect over TLS, and the roots to check the server's certificate against. */
|
|
63
|
+
export type ConnectTlsOptions = ConnectOptions & {
|
|
64
|
+
/** The roots, in PEM, that the server's certificate must chain to, instead of the system's; the system's roots where not given. */
|
|
65
|
+
readonly caCerts?: readonly string[];
|
|
66
|
+
/** The name the certificate must be for, where it is not `hostname` (SNI is sent only for a name, never for an address). */
|
|
67
|
+
readonly serverName?: string;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** A connection: its two ends, its bytes as web streams, and how to end it. */
|
|
71
|
+
export type Conn = {
|
|
72
|
+
/** This end's address. */
|
|
73
|
+
readonly localAddr: NetAddr;
|
|
74
|
+
/** The other end's address. */
|
|
75
|
+
readonly remoteAddr: NetAddr;
|
|
76
|
+
/** The bytes the other end sends; ends when it closes its side; cancelling it closes the connection. */
|
|
77
|
+
readonly readable: ReadableStream<Uint8Array>;
|
|
78
|
+
/** The bytes to send; each write settles once the system has taken it; closing it ends this side (as `closeWrite`). */
|
|
79
|
+
readonly writable: WritableStream<Uint8Array>;
|
|
80
|
+
/** End this side (TCP half-close): the other end reads the end of the data, and this end can still read. */
|
|
81
|
+
closeWrite(): Promise<void>;
|
|
82
|
+
/** Close the connection at once, both ways. Closing it again does nothing. */
|
|
83
|
+
close(): void;
|
|
84
|
+
/** `using conn = await connect(...)` closes it at the end of the block. */
|
|
85
|
+
[Symbol.dispose](): void;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** A listener: its address and its connections. */
|
|
89
|
+
export type Listener = {
|
|
90
|
+
/** Where it listens (the port the system chose where 0 was asked). */
|
|
91
|
+
readonly addr: NetAddr;
|
|
92
|
+
/** The next connection; rejects with `ConnectionAborted` once the listener is closed. */
|
|
93
|
+
accept(): Promise<Conn>;
|
|
94
|
+
/** The connections, one by one, until the listener is closed. */
|
|
95
|
+
[Symbol.asyncIterator](): AsyncIterator<Conn>;
|
|
96
|
+
/** Stop listening; connections already given stay open, those not yet taken are closed. Closing it again does nothing. */
|
|
97
|
+
close(): void;
|
|
98
|
+
/** `using listener = await listen(...)` closes it at the end of the block. */
|
|
99
|
+
[Symbol.dispose](): void;
|
|
100
|
+
/** `await using listener = await listen(...)` closes it at the end of the block. */
|
|
101
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Every TCP socket, and each a TLS listener accepts, is half-open: the end of what the peer sends ends the readable
|
|
106
|
+
* stream alone, and this side writes on until it closes its own (`closeWrite`, `close`). Node's default ends this side too as soon as the
|
|
107
|
+
* peer's end is read, so an echo server whose peer half-closed could lose what it had still to send, by the order in which the peer's end
|
|
108
|
+
* and its own writes happened. A TLS client keeps the TLS socket's own setting, which Node's types do not let one choose.
|
|
109
|
+
*/
|
|
110
|
+
const HALF_OPEN = true;
|
|
111
|
+
|
|
112
|
+
const MAPPED_V4 = "::ffff:";
|
|
113
|
+
|
|
114
|
+
function hostOf(address: string | undefined): string {
|
|
115
|
+
const a = address ?? "";
|
|
116
|
+
return a.startsWith(MAPPED_V4) && net.isIPv4(a.slice(MAPPED_V4.length)) ? a.slice(MAPPED_V4.length) : a;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function wrapSocket(socket: net.Socket): Conn {
|
|
120
|
+
let closed = false;
|
|
121
|
+
let ended = false;
|
|
122
|
+
const readable = new ReadableStream<Uint8Array>(
|
|
123
|
+
{
|
|
124
|
+
start(controller) {
|
|
125
|
+
const finish = (e?: unknown): void => {
|
|
126
|
+
if (ended) return;
|
|
127
|
+
ended = true;
|
|
128
|
+
try {
|
|
129
|
+
if (e === undefined) controller.close();
|
|
130
|
+
else controller.error(mapError(e));
|
|
131
|
+
} catch {
|
|
132
|
+
// The stream was cancelled already.
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
socket.on("data", (chunk: Buffer) => {
|
|
136
|
+
if (ended) return;
|
|
137
|
+
controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
|
|
138
|
+
if ((controller.desiredSize ?? 1) <= 0) socket.pause();
|
|
139
|
+
});
|
|
140
|
+
socket.on("end", () => finish());
|
|
141
|
+
socket.on("error", (e) => finish(e));
|
|
142
|
+
socket.on("close", () => finish());
|
|
143
|
+
},
|
|
144
|
+
pull() {
|
|
145
|
+
socket.resume();
|
|
146
|
+
},
|
|
147
|
+
cancel() {
|
|
148
|
+
ended = true;
|
|
149
|
+
socket.destroy();
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
{ highWaterMark: 1 },
|
|
153
|
+
);
|
|
154
|
+
const writable = new WritableStream<Uint8Array>({
|
|
155
|
+
write(chunk) {
|
|
156
|
+
return new Promise<void>((resolve, reject) => {
|
|
157
|
+
if (socket.destroyed || socket.writableEnded) {
|
|
158
|
+
reject(mapError(Object.assign(new Error("the connection is closed"), { code: "EPIPE" })));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
socket.write(chunk, (e) => (e === undefined || e === null ? resolve() : reject(mapError(e))));
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
close() {
|
|
165
|
+
return endSocket(socket);
|
|
166
|
+
},
|
|
167
|
+
abort() {
|
|
168
|
+
socket.destroy();
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
const close = (): void => {
|
|
172
|
+
if (closed) return;
|
|
173
|
+
closed = true;
|
|
174
|
+
socket.destroy();
|
|
175
|
+
};
|
|
176
|
+
return {
|
|
177
|
+
localAddr: { hostname: hostOf(socket.localAddress), port: socket.localPort ?? 0 },
|
|
178
|
+
remoteAddr: { hostname: hostOf(socket.remoteAddress), port: socket.remotePort ?? 0 },
|
|
179
|
+
readable,
|
|
180
|
+
writable,
|
|
181
|
+
closeWrite: () => endSocket(socket),
|
|
182
|
+
close,
|
|
183
|
+
[Symbol.dispose]: close,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function endSocket(socket: net.Socket): Promise<void> {
|
|
188
|
+
return new Promise<void>((resolve, reject) => {
|
|
189
|
+
if (socket.destroyed || socket.writableFinished) {
|
|
190
|
+
resolve();
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const onError = (e: Error): void => reject(mapError(e));
|
|
194
|
+
socket.once("error", onError);
|
|
195
|
+
socket.end(() => {
|
|
196
|
+
socket.off("error", onError);
|
|
197
|
+
resolve();
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function makeListener(server: net.Server, event: "connection" | "secureConnection", options: ListenOptions): Promise<Listener> {
|
|
203
|
+
const hostname = options.hostname ?? "127.0.0.1";
|
|
204
|
+
const port = options.port ?? 0;
|
|
205
|
+
const queue: net.Socket[] = [];
|
|
206
|
+
const waiting: { readonly resolve: (c: Conn) => void; readonly reject: (e: Error) => void }[] = [];
|
|
207
|
+
let closed = false;
|
|
208
|
+
const closedError = (): Error => new ConnectionAborted("the listener is closed", "", `${hostname}:${port}`);
|
|
209
|
+
server.on(event, (socket: net.Socket) => {
|
|
210
|
+
// An error before the connection is taken is seen by whoever reads it, not thrown out of the process.
|
|
211
|
+
socket.on("error", () => undefined);
|
|
212
|
+
if (closed) {
|
|
213
|
+
socket.destroy();
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const w = waiting.shift();
|
|
217
|
+
if (w === undefined) queue.push(socket);
|
|
218
|
+
else w.resolve(wrapSocket(socket));
|
|
219
|
+
});
|
|
220
|
+
// A client whose TLS handshake fails is that client's problem, not the listener's.
|
|
221
|
+
server.on("tlsClientError", (_e: Error, socket: net.Socket) => socket.destroy());
|
|
222
|
+
const close = (): void => {
|
|
223
|
+
if (closed) return;
|
|
224
|
+
closed = true;
|
|
225
|
+
server.close();
|
|
226
|
+
for (const s of queue.splice(0)) s.destroy();
|
|
227
|
+
for (const w of waiting.splice(0)) w.reject(closedError());
|
|
228
|
+
};
|
|
229
|
+
const accept = (): Promise<Conn> => {
|
|
230
|
+
const s = queue.shift();
|
|
231
|
+
if (s !== undefined) return Promise.resolve(wrapSocket(s));
|
|
232
|
+
if (closed) return Promise.reject(closedError());
|
|
233
|
+
return new Promise<Conn>((resolve, reject) => waiting.push({ resolve, reject }));
|
|
234
|
+
};
|
|
235
|
+
return new Promise<Listener>((resolve, reject) => {
|
|
236
|
+
if (options.signal?.aborted === true) {
|
|
237
|
+
reject(abortError(options.signal));
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
server.once("error", (e) => reject(mapError(e, `${hostname}:${port}`)));
|
|
241
|
+
server.listen(port, hostname, () => {
|
|
242
|
+
const a = server.address() as net.AddressInfo; // A TCP server's address is always an AddressInfo once it listens.
|
|
243
|
+
options.signal?.addEventListener("abort", close, { once: true });
|
|
244
|
+
resolve({
|
|
245
|
+
addr: { hostname: hostOf(a.address), port: a.port },
|
|
246
|
+
accept,
|
|
247
|
+
async *[Symbol.asyncIterator](): AsyncGenerator<Conn> {
|
|
248
|
+
for (;;) {
|
|
249
|
+
let conn: Conn;
|
|
250
|
+
try {
|
|
251
|
+
conn = await accept();
|
|
252
|
+
} catch (e) {
|
|
253
|
+
if (closed) return;
|
|
254
|
+
throw e;
|
|
255
|
+
}
|
|
256
|
+
yield conn;
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
close,
|
|
260
|
+
[Symbol.dispose]: close,
|
|
261
|
+
[Symbol.asyncDispose]: () => {
|
|
262
|
+
close();
|
|
263
|
+
return Promise.resolve();
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Listen for TCP connections; `AddrInUse` where the port is taken. */
|
|
271
|
+
export function listen(options: ListenOptions = {}): Promise<Listener> {
|
|
272
|
+
return makeListener(net.createServer({ pauseOnConnect: false, allowHalfOpen: HALF_OPEN }), "connection", options);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Listen for TLS connections with a certificate and key in PEM; `AddrInUse` where the port is taken. */
|
|
276
|
+
export function listenTls(options: ListenTlsOptions): Promise<Listener> {
|
|
277
|
+
return makeListener(tls.createServer({ cert: options.cert, key: options.key, allowHalfOpen: HALF_OPEN }), "secureConnection", options);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function abortError(signal: AbortSignal): Error {
|
|
281
|
+
const reason: unknown = signal.reason;
|
|
282
|
+
if (reason instanceof Error && reason.name === "TimeoutError") return new TimedOut(reason.message, "ETIMEDOUT", undefined, reason);
|
|
283
|
+
return toError(reason, "the operation was aborted");
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const CERT_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS_/;
|
|
287
|
+
|
|
288
|
+
function connectError(e: unknown, where: string): Error {
|
|
289
|
+
const code: unknown = typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined;
|
|
290
|
+
if (typeof code === "string" && CERT_CODE.test(code)) {
|
|
291
|
+
const message = e instanceof Error ? e.message : code;
|
|
292
|
+
return new InvalidData(`the server's certificate was refused: ${message}`, code, where, e);
|
|
293
|
+
}
|
|
294
|
+
return mapError(e, where);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function open(socket: net.Socket, ready: "connect" | "secureConnect", where: string, signal: AbortSignal | undefined): Promise<Conn> {
|
|
298
|
+
return new Promise<Conn>((resolve, reject) => {
|
|
299
|
+
const onAbort = (): void => {
|
|
300
|
+
socket.destroy();
|
|
301
|
+
if (signal !== undefined) reject(abortError(signal));
|
|
302
|
+
};
|
|
303
|
+
const onError = (e: Error): void => {
|
|
304
|
+
signal?.removeEventListener("abort", onAbort);
|
|
305
|
+
socket.destroy();
|
|
306
|
+
reject(connectError(e, where));
|
|
307
|
+
};
|
|
308
|
+
socket.once("error", onError);
|
|
309
|
+
socket.once(ready, () => {
|
|
310
|
+
signal?.removeEventListener("abort", onAbort);
|
|
311
|
+
socket.off("error", onError);
|
|
312
|
+
resolve(wrapSocket(socket));
|
|
313
|
+
});
|
|
314
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Connect over TCP; `ConnectionRefused` where nothing listens. */
|
|
319
|
+
export function connect(options: ConnectOptions): Promise<Conn> {
|
|
320
|
+
const host = options.hostname ?? "127.0.0.1";
|
|
321
|
+
const where = `${host}:${options.port}`;
|
|
322
|
+
if (options.signal?.aborted === true) return Promise.reject(abortError(options.signal));
|
|
323
|
+
return open(net.connect({ host, port: options.port, allowHalfOpen: HALF_OPEN }), "connect", where, options.signal);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Connect over TLS, checking the server's certificate against the system's roots or the `caCerts` given, and its
|
|
328
|
+
* name against `serverName` or `hostname`; `InvalidData` where the certificate does not check out.
|
|
329
|
+
*/
|
|
330
|
+
export function connectTls(options: ConnectTlsOptions): Promise<Conn> {
|
|
331
|
+
const host = options.hostname ?? "127.0.0.1";
|
|
332
|
+
const where = `${host}:${options.port}`;
|
|
333
|
+
if (options.signal?.aborted === true) return Promise.reject(abortError(options.signal));
|
|
334
|
+
const name = options.serverName ?? host;
|
|
335
|
+
const tlsOptions: tls.ConnectionOptions = {
|
|
336
|
+
host,
|
|
337
|
+
port: options.port,
|
|
338
|
+
rejectUnauthorized: true,
|
|
339
|
+
checkServerIdentity: (_host, cert) => tls.checkServerIdentity(name, cert),
|
|
340
|
+
...(net.isIP(name) === 0 ? { servername: name } : {}),
|
|
341
|
+
...(options.caCerts === undefined ? {} : { ca: [...options.caCerts] }),
|
|
342
|
+
};
|
|
343
|
+
return open(tls.connect(tlsOptions), "secureConnect", where, options.signal);
|
|
344
|
+
}
|