@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/dist/serve.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Where the server listens, or where a request came from. */
|
|
2
|
+
export type NetAddr = {
|
|
3
|
+
readonly hostname: string;
|
|
4
|
+
readonly port: number;
|
|
5
|
+
};
|
|
6
|
+
/** What a handler knows of a request besides the request itself. */
|
|
7
|
+
export type ServeInfo = {
|
|
8
|
+
readonly remoteAddr: NetAddr;
|
|
9
|
+
};
|
|
10
|
+
/** A function from a request to its response. */
|
|
11
|
+
export type ServeHandler = (request: Request, info: ServeInfo) => Response | Promise<Response>;
|
|
12
|
+
/** Where and how to listen. */
|
|
13
|
+
export type ServeOptions = {
|
|
14
|
+
/** The port; 0 (the default) asks the system for a free one. */
|
|
15
|
+
readonly port?: number;
|
|
16
|
+
/** The address to bind; `127.0.0.1` by default, never every interface unless asked. */
|
|
17
|
+
readonly hostname?: string;
|
|
18
|
+
/** Aborting it shuts the server down. */
|
|
19
|
+
readonly signal?: AbortSignal;
|
|
20
|
+
/** The response where the handler throws (a plain 500 by default). */
|
|
21
|
+
readonly onError?: (error: unknown) => Response | Promise<Response>;
|
|
22
|
+
};
|
|
23
|
+
/** A running server. */
|
|
24
|
+
export type Server = {
|
|
25
|
+
/** Where it listens. */
|
|
26
|
+
readonly addr: NetAddr;
|
|
27
|
+
/** Settles when it has shut down. */
|
|
28
|
+
readonly finished: Promise<void>;
|
|
29
|
+
/** Stop listening and close every connection; settles when it has shut down. */
|
|
30
|
+
shutdown(): Promise<void>;
|
|
31
|
+
};
|
|
32
|
+
/** A server that answers each request with what `handler` gives, once its port is bound. `AddrInUse` where the port is taken. */
|
|
33
|
+
export declare function serve(options: ServeOptions, handler: ServeHandler): Promise<Server>;
|
package/dist/serve.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Spec: 0001-net FR-002
|
|
2
|
+
/**
|
|
3
|
+
* An HTTP server whose handler takes a web `Request` and gives a web `Response` on `node:http`, so the same handler
|
|
4
|
+
* runs on Bun and Node (commons 0001-net FR-002). Request bodies and response bodies stream; a client that goes away
|
|
5
|
+
* aborts `request.signal`. `serve` returns a promise, settled once the port is bound, so `addr` is known.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { serve } from "./serve.ts";
|
|
10
|
+
* const server = await serve({ port: 0, hostname: "127.0.0.1" }, (req) => new Response(`you asked for ${new URL(req.url).pathname}`));
|
|
11
|
+
* const text = await (await fetch(`http://127.0.0.1:${server.addr.port}/x`)).text(); // "you asked for /x"
|
|
12
|
+
* await server.shutdown();
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import { createServer } from "node:http";
|
|
18
|
+
import { Readable } from "node:stream";
|
|
19
|
+
import { mapError } from "@intellectual-frontiers/system/errors";
|
|
20
|
+
import { traceServer } from "@intellectual-frontiers/telemetry/host/otel";
|
|
21
|
+
const NO_BODY = new Set(["GET", "HEAD"]);
|
|
22
|
+
function toRequest(req, fallbackHost) {
|
|
23
|
+
const abort = new AbortController();
|
|
24
|
+
const headers = new Headers();
|
|
25
|
+
for (let i = 0; i + 1 < req.rawHeaders.length; i += 2)
|
|
26
|
+
headers.append(req.rawHeaders[i] ?? "", req.rawHeaders[i + 1] ?? "");
|
|
27
|
+
const method = req.method ?? "GET";
|
|
28
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? fallbackHost}`);
|
|
29
|
+
const init = { method, headers, signal: abort.signal };
|
|
30
|
+
if (!NO_BODY.has(method)) {
|
|
31
|
+
init.body = Readable.toWeb(req);
|
|
32
|
+
init.duplex = "half";
|
|
33
|
+
}
|
|
34
|
+
return { request: new Request(url, init), abort };
|
|
35
|
+
}
|
|
36
|
+
async function send(res, response, head) {
|
|
37
|
+
res.statusCode = response.status;
|
|
38
|
+
if (response.statusText !== "")
|
|
39
|
+
res.statusMessage = response.statusText;
|
|
40
|
+
const cookies = response.headers.getSetCookie();
|
|
41
|
+
response.headers.forEach((value, key) => {
|
|
42
|
+
if (key !== "set-cookie")
|
|
43
|
+
res.setHeader(key, value);
|
|
44
|
+
});
|
|
45
|
+
if (cookies.length > 0)
|
|
46
|
+
res.setHeader("set-cookie", cookies);
|
|
47
|
+
if (response.body === null || head) {
|
|
48
|
+
await response.body?.cancel();
|
|
49
|
+
res.end();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
res.flushHeaders();
|
|
53
|
+
const reader = response.body.getReader();
|
|
54
|
+
try {
|
|
55
|
+
for (;;) {
|
|
56
|
+
const { done, value } = await reader.read();
|
|
57
|
+
if (done)
|
|
58
|
+
break;
|
|
59
|
+
if (!res.write(value))
|
|
60
|
+
await new Promise((r) => res.once("drain", r));
|
|
61
|
+
if (res.destroyed)
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
reader.releaseLock();
|
|
67
|
+
res.end();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** A server that answers each request with what `handler` gives, once its port is bound. `AddrInUse` where the port is taken. */
|
|
71
|
+
export function serve(options, handler) {
|
|
72
|
+
const hostname = options.hostname ?? "127.0.0.1";
|
|
73
|
+
const onError = options.onError ?? (() => new Response("internal server error", { status: 500 }));
|
|
74
|
+
const server = createServer((req, res) => {
|
|
75
|
+
const { request, abort } = toRequest(req, `${hostname}:${options.port ?? 0}`);
|
|
76
|
+
res.on("close", () => {
|
|
77
|
+
if (!res.writableFinished)
|
|
78
|
+
abort.abort();
|
|
79
|
+
});
|
|
80
|
+
const remoteAddr = { hostname: req.socket.remoteAddress ?? "", port: req.socket.remotePort ?? 0 };
|
|
81
|
+
void (async () => {
|
|
82
|
+
let response;
|
|
83
|
+
try {
|
|
84
|
+
// Where a telemetry pipeline is installed, an `http.server` span, the child of the request's `traceparent` (0001-net FR-016).
|
|
85
|
+
response = await traceServer(request, () => handler(request, { remoteAddr }), handler);
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
response = await onError(e);
|
|
89
|
+
}
|
|
90
|
+
await send(res, response, request.method === "HEAD").catch(() => res.destroy());
|
|
91
|
+
})();
|
|
92
|
+
});
|
|
93
|
+
const finished = new Promise((resolve) => server.on("close", () => resolve()));
|
|
94
|
+
const shutdown = async () => {
|
|
95
|
+
if (server.listening) {
|
|
96
|
+
server.close();
|
|
97
|
+
server.closeAllConnections();
|
|
98
|
+
}
|
|
99
|
+
await finished;
|
|
100
|
+
};
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
server.once("error", (e) => reject(mapError(e, `${hostname}:${options.port ?? 0}`)));
|
|
103
|
+
server.listen(options.port ?? 0, hostname, () => {
|
|
104
|
+
const a = server.address();
|
|
105
|
+
options.signal?.addEventListener("abort", () => void shutdown(), { once: true });
|
|
106
|
+
resolve({ addr: { hostname: a.address, port: a.port }, finished, shutdown });
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}
|
package/dist/tcp.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { NetAddr } from "./serve.js";
|
|
2
|
+
export type { NetAddr } from "./serve.js";
|
|
3
|
+
/** Where to listen. */
|
|
4
|
+
export type ListenOptions = {
|
|
5
|
+
/** The port; 0 (the default) asks the system for a free one. */
|
|
6
|
+
readonly port?: number;
|
|
7
|
+
/** The address to bind; `127.0.0.1` by default, never every interface unless asked (`0.0.0.0`, `::`). */
|
|
8
|
+
readonly hostname?: string;
|
|
9
|
+
/** Aborting it closes the listener. */
|
|
10
|
+
readonly signal?: AbortSignal;
|
|
11
|
+
};
|
|
12
|
+
/** Where to listen for TLS, and the certificate to answer with. */
|
|
13
|
+
export type ListenTlsOptions = ListenOptions & {
|
|
14
|
+
/** The server's certificate chain, in PEM. */
|
|
15
|
+
readonly cert: string;
|
|
16
|
+
/** The certificate's private key, in PEM. */
|
|
17
|
+
readonly key: string;
|
|
18
|
+
};
|
|
19
|
+
/** Where to connect. */
|
|
20
|
+
export type ConnectOptions = {
|
|
21
|
+
/** The host's name or address; `127.0.0.1` by default. */
|
|
22
|
+
readonly hostname?: string;
|
|
23
|
+
/** The port. */
|
|
24
|
+
readonly port: number;
|
|
25
|
+
/** Aborting it gives up while connecting (`TimedOut` where it is an `AbortSignal.timeout`); a connection made is not affected. */
|
|
26
|
+
readonly signal?: AbortSignal;
|
|
27
|
+
};
|
|
28
|
+
/** Where to connect over TLS, and the roots to check the server's certificate against. */
|
|
29
|
+
export type ConnectTlsOptions = ConnectOptions & {
|
|
30
|
+
/** The roots, in PEM, that the server's certificate must chain to, instead of the system's; the system's roots where not given. */
|
|
31
|
+
readonly caCerts?: readonly string[];
|
|
32
|
+
/** The name the certificate must be for, where it is not `hostname` (SNI is sent only for a name, never for an address). */
|
|
33
|
+
readonly serverName?: string;
|
|
34
|
+
};
|
|
35
|
+
/** A connection: its two ends, its bytes as web streams, and how to end it. */
|
|
36
|
+
export type Conn = {
|
|
37
|
+
/** This end's address. */
|
|
38
|
+
readonly localAddr: NetAddr;
|
|
39
|
+
/** The other end's address. */
|
|
40
|
+
readonly remoteAddr: NetAddr;
|
|
41
|
+
/** The bytes the other end sends; ends when it closes its side; cancelling it closes the connection. */
|
|
42
|
+
readonly readable: ReadableStream<Uint8Array>;
|
|
43
|
+
/** The bytes to send; each write settles once the system has taken it; closing it ends this side (as `closeWrite`). */
|
|
44
|
+
readonly writable: WritableStream<Uint8Array>;
|
|
45
|
+
/** End this side (TCP half-close): the other end reads the end of the data, and this end can still read. */
|
|
46
|
+
closeWrite(): Promise<void>;
|
|
47
|
+
/** Close the connection at once, both ways. Closing it again does nothing. */
|
|
48
|
+
close(): void;
|
|
49
|
+
/** `using conn = await connect(...)` closes it at the end of the block. */
|
|
50
|
+
[Symbol.dispose](): void;
|
|
51
|
+
};
|
|
52
|
+
/** A listener: its address and its connections. */
|
|
53
|
+
export type Listener = {
|
|
54
|
+
/** Where it listens (the port the system chose where 0 was asked). */
|
|
55
|
+
readonly addr: NetAddr;
|
|
56
|
+
/** The next connection; rejects with `ConnectionAborted` once the listener is closed. */
|
|
57
|
+
accept(): Promise<Conn>;
|
|
58
|
+
/** The connections, one by one, until the listener is closed. */
|
|
59
|
+
[Symbol.asyncIterator](): AsyncIterator<Conn>;
|
|
60
|
+
/** Stop listening; connections already given stay open, those not yet taken are closed. Closing it again does nothing. */
|
|
61
|
+
close(): void;
|
|
62
|
+
/** `using listener = await listen(...)` closes it at the end of the block. */
|
|
63
|
+
[Symbol.dispose](): void;
|
|
64
|
+
/** `await using listener = await listen(...)` closes it at the end of the block. */
|
|
65
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
66
|
+
};
|
|
67
|
+
/** Listen for TCP connections; `AddrInUse` where the port is taken. */
|
|
68
|
+
export declare function listen(options?: ListenOptions): Promise<Listener>;
|
|
69
|
+
/** Listen for TLS connections with a certificate and key in PEM; `AddrInUse` where the port is taken. */
|
|
70
|
+
export declare function listenTls(options: ListenTlsOptions): Promise<Listener>;
|
|
71
|
+
/** Connect over TCP; `ConnectionRefused` where nothing listens. */
|
|
72
|
+
export declare function connect(options: ConnectOptions): Promise<Conn>;
|
|
73
|
+
/**
|
|
74
|
+
* Connect over TLS, checking the server's certificate against the system's roots or the `caCerts` given, and its
|
|
75
|
+
* name against `serverName` or `hostname`; `InvalidData` where the certificate does not check out.
|
|
76
|
+
*/
|
|
77
|
+
export declare function connectTls(options: ConnectTlsOptions): Promise<Conn>;
|
package/dist/tcp.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
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
|
+
/**
|
|
31
|
+
* Every TCP socket, and each a TLS listener accepts, is half-open: the end of what the peer sends ends the readable
|
|
32
|
+
* 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
|
|
33
|
+
* 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
|
|
34
|
+
* and its own writes happened. A TLS client keeps the TLS socket's own setting, which Node's types do not let one choose.
|
|
35
|
+
*/
|
|
36
|
+
const HALF_OPEN = true;
|
|
37
|
+
const MAPPED_V4 = "::ffff:";
|
|
38
|
+
function hostOf(address) {
|
|
39
|
+
const a = address ?? "";
|
|
40
|
+
return a.startsWith(MAPPED_V4) && net.isIPv4(a.slice(MAPPED_V4.length)) ? a.slice(MAPPED_V4.length) : a;
|
|
41
|
+
}
|
|
42
|
+
function wrapSocket(socket) {
|
|
43
|
+
let closed = false;
|
|
44
|
+
let ended = false;
|
|
45
|
+
const readable = new ReadableStream({
|
|
46
|
+
start(controller) {
|
|
47
|
+
const finish = (e) => {
|
|
48
|
+
if (ended)
|
|
49
|
+
return;
|
|
50
|
+
ended = true;
|
|
51
|
+
try {
|
|
52
|
+
if (e === undefined)
|
|
53
|
+
controller.close();
|
|
54
|
+
else
|
|
55
|
+
controller.error(mapError(e));
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// The stream was cancelled already.
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
socket.on("data", (chunk) => {
|
|
62
|
+
if (ended)
|
|
63
|
+
return;
|
|
64
|
+
controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
|
|
65
|
+
if ((controller.desiredSize ?? 1) <= 0)
|
|
66
|
+
socket.pause();
|
|
67
|
+
});
|
|
68
|
+
socket.on("end", () => finish());
|
|
69
|
+
socket.on("error", (e) => finish(e));
|
|
70
|
+
socket.on("close", () => finish());
|
|
71
|
+
},
|
|
72
|
+
pull() {
|
|
73
|
+
socket.resume();
|
|
74
|
+
},
|
|
75
|
+
cancel() {
|
|
76
|
+
ended = true;
|
|
77
|
+
socket.destroy();
|
|
78
|
+
},
|
|
79
|
+
}, { highWaterMark: 1 });
|
|
80
|
+
const writable = new WritableStream({
|
|
81
|
+
write(chunk) {
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
if (socket.destroyed || socket.writableEnded) {
|
|
84
|
+
reject(mapError(Object.assign(new Error("the connection is closed"), { code: "EPIPE" })));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
socket.write(chunk, (e) => (e === undefined || e === null ? resolve() : reject(mapError(e))));
|
|
88
|
+
});
|
|
89
|
+
},
|
|
90
|
+
close() {
|
|
91
|
+
return endSocket(socket);
|
|
92
|
+
},
|
|
93
|
+
abort() {
|
|
94
|
+
socket.destroy();
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
const close = () => {
|
|
98
|
+
if (closed)
|
|
99
|
+
return;
|
|
100
|
+
closed = true;
|
|
101
|
+
socket.destroy();
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
localAddr: { hostname: hostOf(socket.localAddress), port: socket.localPort ?? 0 },
|
|
105
|
+
remoteAddr: { hostname: hostOf(socket.remoteAddress), port: socket.remotePort ?? 0 },
|
|
106
|
+
readable,
|
|
107
|
+
writable,
|
|
108
|
+
closeWrite: () => endSocket(socket),
|
|
109
|
+
close,
|
|
110
|
+
[Symbol.dispose]: close,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function endSocket(socket) {
|
|
114
|
+
return new Promise((resolve, reject) => {
|
|
115
|
+
if (socket.destroyed || socket.writableFinished) {
|
|
116
|
+
resolve();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const onError = (e) => reject(mapError(e));
|
|
120
|
+
socket.once("error", onError);
|
|
121
|
+
socket.end(() => {
|
|
122
|
+
socket.off("error", onError);
|
|
123
|
+
resolve();
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function makeListener(server, event, options) {
|
|
128
|
+
const hostname = options.hostname ?? "127.0.0.1";
|
|
129
|
+
const port = options.port ?? 0;
|
|
130
|
+
const queue = [];
|
|
131
|
+
const waiting = [];
|
|
132
|
+
let closed = false;
|
|
133
|
+
const closedError = () => new ConnectionAborted("the listener is closed", "", `${hostname}:${port}`);
|
|
134
|
+
server.on(event, (socket) => {
|
|
135
|
+
// An error before the connection is taken is seen by whoever reads it, not thrown out of the process.
|
|
136
|
+
socket.on("error", () => undefined);
|
|
137
|
+
if (closed) {
|
|
138
|
+
socket.destroy();
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const w = waiting.shift();
|
|
142
|
+
if (w === undefined)
|
|
143
|
+
queue.push(socket);
|
|
144
|
+
else
|
|
145
|
+
w.resolve(wrapSocket(socket));
|
|
146
|
+
});
|
|
147
|
+
// A client whose TLS handshake fails is that client's problem, not the listener's.
|
|
148
|
+
server.on("tlsClientError", (_e, socket) => socket.destroy());
|
|
149
|
+
const close = () => {
|
|
150
|
+
if (closed)
|
|
151
|
+
return;
|
|
152
|
+
closed = true;
|
|
153
|
+
server.close();
|
|
154
|
+
for (const s of queue.splice(0))
|
|
155
|
+
s.destroy();
|
|
156
|
+
for (const w of waiting.splice(0))
|
|
157
|
+
w.reject(closedError());
|
|
158
|
+
};
|
|
159
|
+
const accept = () => {
|
|
160
|
+
const s = queue.shift();
|
|
161
|
+
if (s !== undefined)
|
|
162
|
+
return Promise.resolve(wrapSocket(s));
|
|
163
|
+
if (closed)
|
|
164
|
+
return Promise.reject(closedError());
|
|
165
|
+
return new Promise((resolve, reject) => waiting.push({ resolve, reject }));
|
|
166
|
+
};
|
|
167
|
+
return new Promise((resolve, reject) => {
|
|
168
|
+
if (options.signal?.aborted === true) {
|
|
169
|
+
reject(abortError(options.signal));
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
server.once("error", (e) => reject(mapError(e, `${hostname}:${port}`)));
|
|
173
|
+
server.listen(port, hostname, () => {
|
|
174
|
+
const a = server.address(); // A TCP server's address is always an AddressInfo once it listens.
|
|
175
|
+
options.signal?.addEventListener("abort", close, { once: true });
|
|
176
|
+
resolve({
|
|
177
|
+
addr: { hostname: hostOf(a.address), port: a.port },
|
|
178
|
+
accept,
|
|
179
|
+
async *[Symbol.asyncIterator]() {
|
|
180
|
+
for (;;) {
|
|
181
|
+
let conn;
|
|
182
|
+
try {
|
|
183
|
+
conn = await accept();
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
if (closed)
|
|
187
|
+
return;
|
|
188
|
+
throw e;
|
|
189
|
+
}
|
|
190
|
+
yield conn;
|
|
191
|
+
}
|
|
192
|
+
},
|
|
193
|
+
close,
|
|
194
|
+
[Symbol.dispose]: close,
|
|
195
|
+
[Symbol.asyncDispose]: () => {
|
|
196
|
+
close();
|
|
197
|
+
return Promise.resolve();
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
/** Listen for TCP connections; `AddrInUse` where the port is taken. */
|
|
204
|
+
export function listen(options = {}) {
|
|
205
|
+
return makeListener(net.createServer({ pauseOnConnect: false, allowHalfOpen: HALF_OPEN }), "connection", options);
|
|
206
|
+
}
|
|
207
|
+
/** Listen for TLS connections with a certificate and key in PEM; `AddrInUse` where the port is taken. */
|
|
208
|
+
export function listenTls(options) {
|
|
209
|
+
return makeListener(tls.createServer({ cert: options.cert, key: options.key, allowHalfOpen: HALF_OPEN }), "secureConnection", options);
|
|
210
|
+
}
|
|
211
|
+
function abortError(signal) {
|
|
212
|
+
const reason = signal.reason;
|
|
213
|
+
if (reason instanceof Error && reason.name === "TimeoutError")
|
|
214
|
+
return new TimedOut(reason.message, "ETIMEDOUT", undefined, reason);
|
|
215
|
+
return toError(reason, "the operation was aborted");
|
|
216
|
+
}
|
|
217
|
+
const CERT_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS_/;
|
|
218
|
+
function connectError(e, where) {
|
|
219
|
+
const code = typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined;
|
|
220
|
+
if (typeof code === "string" && CERT_CODE.test(code)) {
|
|
221
|
+
const message = e instanceof Error ? e.message : code;
|
|
222
|
+
return new InvalidData(`the server's certificate was refused: ${message}`, code, where, e);
|
|
223
|
+
}
|
|
224
|
+
return mapError(e, where);
|
|
225
|
+
}
|
|
226
|
+
function open(socket, ready, where, signal) {
|
|
227
|
+
return new Promise((resolve, reject) => {
|
|
228
|
+
const onAbort = () => {
|
|
229
|
+
socket.destroy();
|
|
230
|
+
if (signal !== undefined)
|
|
231
|
+
reject(abortError(signal));
|
|
232
|
+
};
|
|
233
|
+
const onError = (e) => {
|
|
234
|
+
signal?.removeEventListener("abort", onAbort);
|
|
235
|
+
socket.destroy();
|
|
236
|
+
reject(connectError(e, where));
|
|
237
|
+
};
|
|
238
|
+
socket.once("error", onError);
|
|
239
|
+
socket.once(ready, () => {
|
|
240
|
+
signal?.removeEventListener("abort", onAbort);
|
|
241
|
+
socket.off("error", onError);
|
|
242
|
+
resolve(wrapSocket(socket));
|
|
243
|
+
});
|
|
244
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
/** Connect over TCP; `ConnectionRefused` where nothing listens. */
|
|
248
|
+
export function connect(options) {
|
|
249
|
+
const host = options.hostname ?? "127.0.0.1";
|
|
250
|
+
const where = `${host}:${options.port}`;
|
|
251
|
+
if (options.signal?.aborted === true)
|
|
252
|
+
return Promise.reject(abortError(options.signal));
|
|
253
|
+
return open(net.connect({ host, port: options.port, allowHalfOpen: HALF_OPEN }), "connect", where, options.signal);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Connect over TLS, checking the server's certificate against the system's roots or the `caCerts` given, and its
|
|
257
|
+
* name against `serverName` or `hostname`; `InvalidData` where the certificate does not check out.
|
|
258
|
+
*/
|
|
259
|
+
export function connectTls(options) {
|
|
260
|
+
const host = options.hostname ?? "127.0.0.1";
|
|
261
|
+
const where = `${host}:${options.port}`;
|
|
262
|
+
if (options.signal?.aborted === true)
|
|
263
|
+
return Promise.reject(abortError(options.signal));
|
|
264
|
+
const name = options.serverName ?? host;
|
|
265
|
+
const tlsOptions = {
|
|
266
|
+
host,
|
|
267
|
+
port: options.port,
|
|
268
|
+
rejectUnauthorized: true,
|
|
269
|
+
checkServerIdentity: (_host, cert) => tls.checkServerIdentity(name, cert),
|
|
270
|
+
...(net.isIP(name) === 0 ? { servername: name } : {}),
|
|
271
|
+
...(options.caCerts === undefined ? {} : { ca: [...options.caCerts] }),
|
|
272
|
+
};
|
|
273
|
+
return open(tls.connect(tlsOptions), "secureConnect", where, options.signal);
|
|
274
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intellectual-frontiers/net",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The network as one typed library: downloads that retry and resume, an HTTP server over web Request and Response, typed HTTP clients with recorded transports and AWS signing, TCP and TLS, DNS records, and ACME certificates by DNS-01; the same code on Bun and Node 26.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=26"
|
|
9
|
+
},
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"types": "./dist/mod.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/mod.d.ts",
|
|
15
|
+
"bun": "./src/mod.ts",
|
|
16
|
+
"default": "./dist/mod.js"
|
|
17
|
+
},
|
|
18
|
+
"./net": {
|
|
19
|
+
"types": "./dist/net.d.ts",
|
|
20
|
+
"bun": "./src/net.ts",
|
|
21
|
+
"default": "./dist/net.js"
|
|
22
|
+
},
|
|
23
|
+
"./tcp": {
|
|
24
|
+
"types": "./dist/tcp.d.ts",
|
|
25
|
+
"bun": "./src/tcp.ts",
|
|
26
|
+
"default": "./dist/tcp.js"
|
|
27
|
+
},
|
|
28
|
+
"./dns": {
|
|
29
|
+
"types": "./dist/dns.d.ts",
|
|
30
|
+
"bun": "./src/dns.ts",
|
|
31
|
+
"default": "./dist/dns.js"
|
|
32
|
+
},
|
|
33
|
+
"./http-client": {
|
|
34
|
+
"types": "./dist/http-client.d.ts",
|
|
35
|
+
"bun": "./src/http-client.ts",
|
|
36
|
+
"default": "./dist/http-client.js"
|
|
37
|
+
},
|
|
38
|
+
"./serve": {
|
|
39
|
+
"types": "./dist/serve.d.ts",
|
|
40
|
+
"bun": "./src/serve.ts",
|
|
41
|
+
"default": "./dist/serve.js"
|
|
42
|
+
},
|
|
43
|
+
"./acme": {
|
|
44
|
+
"types": "./dist/acme.d.ts",
|
|
45
|
+
"bun": "./src/acme.ts",
|
|
46
|
+
"default": "./dist/acme.js"
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"@intellectual-frontiers/core": "0.1.2",
|
|
51
|
+
"@intellectual-frontiers/crypto": "0.1.2",
|
|
52
|
+
"@intellectual-frontiers/formats": "0.1.2",
|
|
53
|
+
"@intellectual-frontiers/system": "0.1.2",
|
|
54
|
+
"@intellectual-frontiers/telemetry": "0.1.2"
|
|
55
|
+
},
|
|
56
|
+
"files": [
|
|
57
|
+
"dist",
|
|
58
|
+
"src",
|
|
59
|
+
"README.md",
|
|
60
|
+
"LICENSE"
|
|
61
|
+
],
|
|
62
|
+
"repository": {
|
|
63
|
+
"type": "git",
|
|
64
|
+
"url": "git+https://github.com/intellectual-frontiers/.github.git",
|
|
65
|
+
"directory": "commons/net"
|
|
66
|
+
},
|
|
67
|
+
"homepage": "https://github.com/intellectual-frontiers/.github/tree/main/commons/net",
|
|
68
|
+
"bugs": {
|
|
69
|
+
"url": "https://github.com/intellectual-frontiers/.github/issues"
|
|
70
|
+
},
|
|
71
|
+
"publishConfig": {
|
|
72
|
+
"access": "public"
|
|
73
|
+
}
|
|
74
|
+
}
|