@webpodjs/net-worker 0.2.7 → 0.3.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/README.md CHANGED
@@ -6,7 +6,8 @@ produces frames into `toEngine`.
6
6
 
7
7
  - **Gateway** 192.168.127.1/24: DHCP (the guest gets 192.168.127.2, router and DNS = gateway, MTU
8
8
  option 26), DNS answering fake IPs (198.18.0.0/16, stable per name for the pod's lifetime; AAAA
9
- gets an empty answer).
9
+ gets an empty answer); with a relay, the other record types (SRV, TXT, MX, ...) from an upstream
10
+ resolver through it ("DNS" below).
10
11
  - **Egress** (no proxy variables needed): HTTP/1.1 is proxied transparently through `fetch()`,
11
12
  HTTPS too after TLS interception with the pod CA, WebSocket upgrades through the browser's
12
13
  `WebSocket`; optionally a CORS proxy (docs/cors-proxy-protocol.md) and an L4 relay for raw TCP
@@ -74,6 +75,7 @@ interception without flags.
74
75
  | `mode` | `"browser"` (default) or `"none"`: HTTP, HTTPS and WebSocket are denied unless a route allows them; no relay default |
75
76
  | `corsProxy` | URL or `{ url, token? }` of a webpod CORS proxy, for `via: "cors-proxy"` routes |
76
77
  | `relay` | `{ url, token? , getToken? }`: an L4 relay; raw TCP goes through it by default. `getToken()` runs in the page and is called for each relay connection (also after the relay rejects an expired token) |
78
+ | `dns` | `{ upstream? }` or `false`: with a relay, the upstream resolver of the records other than A and AAAA ("DNS" below); `upstream`: `"host:port"` (default `"9.9.9.9:53"`), `"[ipv6]:port"`, or a name the relay resolves. `false`: none; none either while the routes do not send TCP to the upstream through the relay (a deny rule for it, `mode: "none"` without a route) |
77
79
  | `routes` | `[{ host?, ports?, protocol?, via, stripHeaders? }]`, first match wins. `host`: `example.com`, `*.example.com`, `10.0.0.0/8` or `*`; `ports`: one port or `[lo, hi]`; `protocol`: `http`, `tls`, `websocket`, `tcp`, `udp`; `via`: `fetch`, `websocket`, `cors-proxy`, `relay`, `deny`. `stripHeaders: "non-safelisted"` (with `via: "fetch"`): only CORS-safelisted request headers, so no preflight (registry.npmjs.org refuses preflights); all others, `Authorization` too, are dropped |
78
80
  | `lan`, `hostname` | join the page LAN of that name (see below); `lan: { name, allow }` limits what this guest may open connections to |
79
81
  | `mtu` | link MTU, default 65520 like the QEMU-Wasm engine's virtio-net `host_mtu` (both must match; large frames are about 3x faster than 1500 under TCG) |
@@ -91,6 +93,34 @@ protocol: "udp", via: "relay" }`). Relayed UDP is one relay stream per guest 4-t
91
93
  per datagram, closed after 60 s idle; the Cloudflare relay refuses UDP. A `tls` route to the relay
92
94
  tunnels HTTPS end to end instead of intercepting it.
93
95
 
96
+ ### DNS
97
+
98
+ The gateway answers A queries with fake IPs and AAAA with no data, whatever the name. With a relay
99
+ (and `dns` not `false`, and routes that send TCP to the upstream through the relay, as by default
100
+ in `mode: "browser"`: a deny rule for it, or `mode: "none"` without a route, turns it off), the
101
+ other record types (SRV, TXT, MX, NS, CNAME, CAA, NAPTR, SOA, TLSA, ANY,
102
+ and PTR of addresses it did not give) come from `dns.upstream` (default `9.9.9.9:53`, Quad9:
103
+ Cloudflare's resolvers are out of reach of a relay on Cloudflare Workers) over DNS over TCP (RFC
104
+ 7766): one relay stream, opened at the first query and closed after 30 s without one, its queries
105
+ pipelined; a query without an answer after 5 s fails (SERVFAIL), one whose stream ends goes once
106
+ more on a new one (1 s later when it failed: the relay reconnects first). HTTPS and SVCB records
107
+ stay without data (their address hints and ECH keys would take clients past the fake IPs and the TLS
108
+ interception). At most 64 queries are in flight and 1024 questions wait; the guest has at most 16
109
+ DNS over TCP connections to the gateway. A and AAAA records are taken out of every answer (CNAMEs stay): the program
110
+ asks the gateway for the A of a name next and gets its fake IP, so its connections go by name
111
+ through the routes and deny rules. Answers are cached by name and type for their TTL (at most 300
112
+ s; NXDOMAIN and no data for the SOA's minimum, at most 60 s; 512 answers or 256 KiB in all) and
113
+ shared with host processes (`query` below). A guest's UDP answer fits the size its query offers
114
+ (EDNS0, at most 4096; else 512 bytes), truncated with TC otherwise; the gateway answers DNS over TCP
115
+ too (c-ares asks again there). The gateway's own names (`host.webpod.internal`, LAN peers,
116
+ `localhost`) never go upstream. When the relay refuses the upstream (its destination policy, a
117
+ token's `allow`: RST 4), queries fail at once for 30 s (SERVFAIL; ESERVFAIL with the reason for host
118
+ processes) instead of timing out. Without a relay, or with `dns: false`, they have no data, as
119
+ before.
120
+
121
+ Privacy: the names go to the relay's operator and to the upstream resolver, which sees the relay's
122
+ address, not the user's. `dns: false` keeps them in the pod.
123
+
94
124
  ## Messages
95
125
 
96
126
  Host -> Worker:
@@ -140,6 +170,7 @@ hunting and diagnostics panels. Connection gauges drop back to 0 when traffic st
140
170
  | `buffered` | bytes held in connection buffers (both directions) |
141
171
  | `queuedFrames` | frames queued in the gateway and the Worker (from and to the guest, for peers) |
142
172
  | `fetches`, `egressWebsockets`, `queuedCompletions` | `fetch()` calls in flight, browser WebSockets, egress results not yet applied |
173
+ | `queuedBytes`, `heldBytes`, `heldPeak` | response body bytes among those results; read from `fetch()` and not copied into wasm memory yet (a chunk is copied as the stack makes room), now and at most |
143
174
  | `relayConnections`, `relayStreams` | WebSockets to relays, streams on them |
144
175
  | `fakeIps`, `peers`, `peerPorts`, `pendingInbound` | names holding a fake IP, LAN peers in the stack and their ports, inbound ports waiting for attach |
145
176
  | `wasmMemory` | bytes of wasm memory (it never shrinks) |
@@ -174,8 +205,11 @@ same address: the same router (routes, `mode`, CORS proxy, relay, deny), sniffin
174
205
  resolve in the guest's DNS (fake IPs). Loopback is refused (localhost is not the browser's).
175
206
 
176
207
  On the port, the process sends `{ type: "lookup", id, host }` (answered `{ type: "lookup", id, address }`, IPv4),
208
+ `{ type: "query", id, name, qtype }` (a record type other than A and AAAA, the DNS type's number; "DNS" above:
209
+ answered `{ type: "query", id, result }`, `result` what node's `dns.resolve*` gives, or `{ type: "query", id, code,
210
+ reason? }`, c-ares's code, `reason` when the pod is the cause: no resolver, the relay refused, no answer),
177
211
  `{ type: "connect", id, address, port }` (answered `connected`, or `reset` with a reason), `{ type: "tls", id,
178
- servername }` before any data (answered `{ type: "tls", id, error? }`), `{ type: "data", id, data }`, `{ type: "end", id }`
212
+ servername }` before any data (answered `{ type: "tls", id, error? }`, below), `{ type: "data", id, data }`, `{ type: "end", id }`
179
213
  (FIN) and `{ type: "close", id }` (destroy); it acknowledges what it took with `{ type: "ack", id, bytes }` (at most
180
214
  1 MiB is unacknowledged). This Worker sends `{ type: "data", id, data }`, `{ type: "end", id }` and
181
215
  `{ type: "reset", id, reason }`.
@@ -189,8 +223,8 @@ previews, pod.net.connect, a preview's WebSocket) and the guest's TCP connection
189
223
  (the agent's forwarder) go to the process instead of the guest: `{ type: "accept", id, port }` on its port, with an id
190
224
  this Worker picks (negative), then the same `data` / `end` / `reset` and `ack` / `close` as a connection of its own.
191
225
  Registrations are by the current listener: after an unlisten, new connections go to the guest again (vite 8 listens,
192
- closes and listens again on its port); accepted ones go on. The gateway serves only UDP itself (DNS 53, DHCP 67), so
193
- no port of its own is taken by a host listener. `host-socket-close` ends the process's listens too.
226
+ closes and listens again on its port); accepted ones go on. The gateway serves only UDP itself (DNS 53, DHCP 67), and
227
+ TCP 53 when it forwards DNS, which a host listener on 53 takes over. `host-socket-close` ends the process's listens too.
194
228
 
195
229
  **The pod's localhost.** A process's `connect` to `127.0.0.1` or `::1` (T95): where a host process listens on that
196
230
  port, the two connections are joined here (the listener gets `accept`); otherwise this Worker asks the host for the
@@ -210,6 +244,12 @@ TLS is not done in the process (design docs/experiments/e4-host-node.md §7.1):
210
244
  plaintext of TLS, which is handled as intercepted HTTPS (the browser checks the certificate). TLS that does not carry
211
245
  HTTP, TLS whose route is a relay (which needs the TLS bytes) and STARTTLS are refused, the reason starting with
212
246
  `unsupported`.
247
+ On a connection to the pod's localhost joined to a host listener, `tls` is answered at once when that listener is a
248
+ TLS server (https, tls, http2's secure server), whose process sent `{ type: "tls-listen", port, certs }` after its
249
+ listen: both ends carry plaintext (that server takes it as TLS, M3), and the answer is `{ type: "tls", id, local: true,
250
+ certs }`, the server's certificate chain (DER, or null) for the client to check as node would. To any other listener
251
+ (a proxy or a port forwarder, which would pass the plaintext on, to the network too) and to the guest's localhost it
252
+ is refused (T142).
213
253
 
214
254
  ## The pod CA
215
255
 
@@ -50,6 +50,12 @@ export class NetPod {
50
50
  * The IPv4 address a host process gets for `name` (the guest's DNS answer).
51
51
  */
52
52
  host_lookup(name: string): string;
53
+ /**
54
+ * A host process's query (dns.resolveSrv, ...; T200) for name's records of DNS type `qtype`
55
+ * (33: SRV, ...; a reverse lookup is a PTR query of its in-addr.arpa name). The answer comes
56
+ * from [`Self::take_host_dns`].
57
+ */
58
+ host_query(id: number, name: string, qtype: number): void;
53
59
  host_send(id: number, data: Uint8Array | number[]): void;
54
60
  /**
55
61
  * `tls.connect` on a host connection: returns the reason it cannot, or undefined.
@@ -58,10 +64,11 @@ export class NetPod {
58
64
  host_unlisten(port: number): void;
59
65
  /**
60
66
  * `network`: `{ mode?: "browser" | "none", mtu?, corsProxy?: { url, token? }, relay?: { url,
61
- * token? }, routes?: [{ host?, ports?: [lo, hi], protocol?, via, stripHeaders? }] }` (see
62
- * packages/net-worker/README.md). `ca_bundle`: a previously exported CA (PEM, certificate and
63
- * key) or empty to generate one. `get_token`: called for relay tokens when `relay.token` is
64
- * absent (returns a string or a Promise). `unix_secs`: wall clock (wasm has none).
67
+ * token? }, dns?: { upstream? } | false, routes?: [{ host?, ports?: [lo, hi], protocol?, via,
68
+ * stripHeaders? }] }` (see packages/net-worker/README.md). `ca_bundle`: a previously exported
69
+ * CA (PEM, certificate and key) or empty to generate one. `get_token`: called for relay tokens
70
+ * when `relay.token` is absent (returns a string or a Promise). `unix_secs`: wall clock (wasm has
71
+ * none).
65
72
  */
66
73
  constructor(network: any, ca_bundle: string, get_token: Function | null | undefined, unix_secs: number);
67
74
  /**
@@ -100,6 +107,13 @@ export class NetPod {
100
107
  * Guest frames for peers: `[[peerId, Uint8Array], ...]`, to post to their Workers.
101
108
  */
102
109
  take_forwarded(): Array<any>;
110
+ /**
111
+ * Host processes' answers: `[[id, code, null, reason?] | [id, null, result], ...]`, `code`
112
+ * c-ares's (ENODATA, ENOTFOUND, ESERVFAIL, ETIMEOUT, ...), `result` what node's resolve* gives
113
+ * (resolveSoa's object, the others' lists), `reason` why it failed when the relay is the
114
+ * cause.
115
+ */
116
+ take_host_dns(): Array<any>;
103
117
  /**
104
118
  * What happened to host connections since the last call: `[[id, "data", Uint8Array] |
105
119
  * [id, "end"] | [id, "reset", reason] | [id, "accept", port], ...]`.
@@ -130,6 +144,7 @@ export interface InitOutput {
130
144
  readonly netpod_host_end: (a: number, b: number) => void;
131
145
  readonly netpod_host_listen: (a: number, b: number) => [number, number, number];
132
146
  readonly netpod_host_lookup: (a: number, b: number, c: number) => [number, number];
147
+ readonly netpod_host_query: (a: number, b: number, c: number, d: number, e: number) => void;
133
148
  readonly netpod_host_send: (a: number, b: number, c: number, d: number) => void;
134
149
  readonly netpod_host_start_tls: (a: number, b: number, c: number, d: number) => [number, number];
135
150
  readonly netpod_host_unlisten: (a: number, b: number) => void;
@@ -144,6 +159,7 @@ export interface InitOutput {
144
159
  readonly netpod_stats: (a: number) => any;
145
160
  readonly netpod_take: (a: number) => any;
146
161
  readonly netpod_take_forwarded: (a: number) => any;
162
+ readonly netpod_take_host_dns: (a: number) => any;
147
163
  readonly netpod_take_host_events: (a: number) => any;
148
164
  readonly set_logger: (a: any, b: number, c: number) => void;
149
165
  readonly ring_core_0_17_14__bn_mul_mont: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
@@ -159,6 +159,21 @@ export class NetPod {
159
159
  wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
160
160
  }
161
161
  }
162
+ /**
163
+ * A host process's query (dns.resolveSrv, ...; T200) for name's records of DNS type `qtype`
164
+ * (33: SRV, ...; a reverse lookup is a PTR query of its in-addr.arpa name). The answer comes
165
+ * from [`Self::take_host_dns`].
166
+ * @param {number} id
167
+ * @param {string} name
168
+ * @param {number} qtype
169
+ */
170
+ host_query(id, name, qtype) {
171
+ const val2 = +id;
172
+ const val3 = +qtype;
173
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
174
+ const len0 = WASM_VECTOR_LEN;
175
+ wasm.netpod_host_query(this.__wbg_ptr, val2, ptr0, len0, val3);
176
+ }
162
177
  /**
163
178
  * @param {number} id
164
179
  * @param {Uint8Array | number[]} data
@@ -195,10 +210,11 @@ export class NetPod {
195
210
  }
196
211
  /**
197
212
  * `network`: `{ mode?: "browser" | "none", mtu?, corsProxy?: { url, token? }, relay?: { url,
198
- * token? }, routes?: [{ host?, ports?: [lo, hi], protocol?, via, stripHeaders? }] }` (see
199
- * packages/net-worker/README.md). `ca_bundle`: a previously exported CA (PEM, certificate and
200
- * key) or empty to generate one. `get_token`: called for relay tokens when `relay.token` is
201
- * absent (returns a string or a Promise). `unix_secs`: wall clock (wasm has none).
213
+ * token? }, dns?: { upstream? } | false, routes?: [{ host?, ports?: [lo, hi], protocol?, via,
214
+ * stripHeaders? }] }` (see packages/net-worker/README.md). `ca_bundle`: a previously exported
215
+ * CA (PEM, certificate and key) or empty to generate one. `get_token`: called for relay tokens
216
+ * when `relay.token` is absent (returns a string or a Promise). `unix_secs`: wall clock (wasm has
217
+ * none).
202
218
  * @param {any} network
203
219
  * @param {string} ca_bundle
204
220
  * @param {Function | null | undefined} get_token
@@ -297,6 +313,17 @@ export class NetPod {
297
313
  const ret = wasm.netpod_take_forwarded(this.__wbg_ptr);
298
314
  return ret;
299
315
  }
316
+ /**
317
+ * Host processes' answers: `[[id, code, null, reason?] | [id, null, result], ...]`, `code`
318
+ * c-ares's (ENODATA, ENOTFOUND, ESERVFAIL, ETIMEOUT, ...), `result` what node's resolve* gives
319
+ * (resolveSoa's object, the others' lists), `reason` why it failed when the relay is the
320
+ * cause.
321
+ * @returns {Array<any>}
322
+ */
323
+ take_host_dns() {
324
+ const ret = wasm.netpod_take_host_dns(this.__wbg_ptr);
325
+ return ret;
326
+ }
300
327
  /**
301
328
  * What happened to host connections since the last call: `[[id, "data", Uint8Array] |
302
329
  * [id, "end"] | [id, "reset", reason] | [id, "accept", port], ...]`.
@@ -811,17 +838,17 @@ function __wbg_get_imports() {
811
838
  return ret;
812
839
  },
813
840
  __wbindgen_generic_0000000000000001: function(arg0, arg1) {
814
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 40, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
841
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 46, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
815
842
  const ret = makeMutClosure(arg0, arg1, wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue______true_);
816
843
  return ret;
817
844
  },
818
845
  __wbindgen_generic_0000000000000002: function(arg0, arg1) {
819
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 808, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
846
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 816, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
820
847
  const ret = makeMutClosure(arg0, arg1, wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__core_6a51abefd5362b2___result__Result_____wasm_bindgen_5a2380350bab5903___JsError___true_);
821
848
  return ret;
822
849
  },
823
850
  __wbindgen_generic_0000000000000003: function(arg0, arg1) {
824
- // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 42, ret: Externref, inner_ret: Some(Externref) }, mutable: true }) -> Externref`.
851
+ // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 48, ret: Externref, inner_ret: Some(Externref) }, mutable: true }) -> Externref`.
825
852
  const ret = makeMutClosure(arg0, arg1, wasm_bindgen_5a2380350bab5903___convert__closures_____invoke___wasm_bindgen_5a2380350bab5903___JsValue__true_);
826
853
  return ret;
827
854
  },
Binary file
@@ -14,6 +14,7 @@ export const netpod_host_connect_local: (a: number, b: number) => [number, numbe
14
14
  export const netpod_host_end: (a: number, b: number) => void;
15
15
  export const netpod_host_listen: (a: number, b: number) => [number, number, number];
16
16
  export const netpod_host_lookup: (a: number, b: number, c: number) => [number, number];
17
+ export const netpod_host_query: (a: number, b: number, c: number, d: number, e: number) => void;
17
18
  export const netpod_host_send: (a: number, b: number, c: number, d: number) => void;
18
19
  export const netpod_host_start_tls: (a: number, b: number, c: number, d: number) => [number, number];
19
20
  export const netpod_host_unlisten: (a: number, b: number) => void;
@@ -28,6 +29,7 @@ export const netpod_set_unix_time: (a: number, b: number) => void;
28
29
  export const netpod_stats: (a: number) => any;
29
30
  export const netpod_take: (a: number) => any;
30
31
  export const netpod_take_forwarded: (a: number) => any;
32
+ export const netpod_take_host_dns: (a: number) => any;
31
33
  export const netpod_take_host_events: (a: number) => any;
32
34
  export const set_logger: (a: any, b: number, c: number) => void;
33
35
  export const ring_core_0_17_14__bn_mul_mont: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
package/dist/worker.js CHANGED
@@ -34,7 +34,20 @@ const hostSockets = new Map();
34
34
  const pendingHostSockets = [];
35
35
  /** stack connection id -> [host socket id, local id] */
36
36
  const hostConns = new Map();
37
- /** Ports host processes listen on: port -> { owner: host socket id, count } (a process may listen on several addresses). */
37
+ /** Host processes' DNS queries (T200): stack query id -> [host socket id, the process's id]. */
38
+ const hostQueries = new Map();
39
+ let nextQuery = 0;
40
+ /**
41
+ * Host connections to the pod's localhost: stack id -> { kind: "local", port, owner } (joined to a host process's
42
+ * listener) or { kind: "guest" } (the guest's localhost). TLS on a local one is plaintext at both ends (host mode
43
+ * does no TLS, its servers neither: M3), when the listener is a TLS server: on any other the plaintext would go on
44
+ * as it is (a proxy's or a tunnel's to the network).
45
+ */
46
+ const loopbackConns = new Map();
47
+ /**
48
+ * Ports host processes listen on: port -> { owner: host socket id, count, tls } (a process may listen on several
49
+ * addresses; tls: a TLS server, whose process said so with tls-listen).
50
+ */
38
51
  const hostListeners = new Map();
39
52
  /** Local ids of accepted connections are this Worker's: negative, apart from the ids processes pick. */
40
53
  let nextAccepted = 0;
@@ -94,8 +107,13 @@ function openHostSocket({ id, port }) {
94
107
  case "lookup":
95
108
  reply({ type: "lookup", id: m.id, address: pod.host_lookup(String(m.host)) });
96
109
  break;
110
+ case "query":
111
+ hostQueries.set(++nextQuery, [id, m.id]);
112
+ pod.host_query(nextQuery, String(m.name), m.qtype);
113
+ break;
97
114
  case "connect": {
98
- const attach = (c) => {
115
+ const attach = (c, loopback) => {
116
+ if (loopback) loopbackConns.set(c, loopback);
99
117
  hs.conns.set(m.id, c);
100
118
  hostConns.set(c, [id, m.id]);
101
119
  reply({ type: "connected", id: m.id });
@@ -105,13 +123,13 @@ function openHostSocket({ id, port }) {
105
123
  if (m.address === "127.0.0.1" || m.address === "::1") {
106
124
  if (hostListeners.has(m.port)) {
107
125
  try {
108
- attach(pod.host_connect_local(m.port));
126
+ attach(pod.host_connect_local(m.port), { kind: "local", port: m.port, owner: hostListeners.get(m.port).owner });
109
127
  } catch (e) {
110
128
  reply({ type: "reset", id: m.id, reason: String(e?.message ?? e) });
111
129
  }
112
130
  } else
113
131
  guestLocalhost(m.port).then(
114
- (via) => (hostSockets.get(id) === hs && pod ? attach(pod.host_connect_guest(via)) : undefined),
132
+ (via) => (hostSockets.get(id) === hs && pod ? attach(pod.host_connect_guest(via), { kind: "guest" }) : undefined),
115
133
  (e) => reply({ type: "reset", id: m.id, reason: String(e?.message ?? e) }),
116
134
  );
117
135
  break;
@@ -127,8 +145,26 @@ function openHostSocket({ id, port }) {
127
145
  break;
128
146
  }
129
147
  case "tls": {
130
- const error = conn === undefined ? "no such connection" : pod.host_start_tls(conn, m.servername ?? undefined);
131
- reply({ type: "tls", id: m.id, ...(error ? { error } : {}) });
148
+ const loopback = loopbackConns.get(conn);
149
+ const listener = loopback?.kind === "local" ? hostListeners.get(loopback.port) : undefined;
150
+ const error =
151
+ conn === undefined
152
+ ? "no such connection"
153
+ : loopback?.kind === "local"
154
+ ? listener?.tls && listener.owner === loopback.owner
155
+ ? undefined
156
+ : "unsupported: TLS to a server on the pod's localhost that is not a host process's TLS server (host mode does no TLS: through a proxy or a tunnel it would go on in plaintext)"
157
+ : loopback?.kind === "guest"
158
+ ? "unsupported: TLS to the guest's localhost needs regular node"
159
+ : pod.host_start_tls(conn, m.servername ?? undefined);
160
+ // To a host process's TLS server: its certificate chain, which the client checks as node would.
161
+ reply({ type: "tls", id: m.id, ...(error ? { error } : loopback?.kind === "local" ? { local: true, certs: listener.certs } : {}) });
162
+ break;
163
+ }
164
+ // The process's server on port is a TLS server (it takes plaintext as TLS): a host client's TLS may go to it.
165
+ case "tls-listen": {
166
+ const l = hostListeners.get(m.port);
167
+ if (l?.owner === id) Object.assign(l, { tls: true, certs: m.certs ?? null });
132
168
  break;
133
169
  }
134
170
  case "data":
@@ -145,6 +181,7 @@ function openHostSocket({ id, port }) {
145
181
  pod.host_abort(conn);
146
182
  hs.conns.delete(m.id);
147
183
  hostConns.delete(conn);
184
+ loopbackConns.delete(conn);
148
185
  }
149
186
  break;
150
187
  }
@@ -185,6 +222,7 @@ function closeHostSocket(id) {
185
222
  if (local < 0) pod?.host_end(c);
186
223
  pod?.host_abort(c);
187
224
  hostConns.delete(c);
225
+ loopbackConns.delete(c);
188
226
  }
189
227
  hs.port.close();
190
228
  wake?.();
@@ -215,10 +253,21 @@ function deliverHostEvents() {
215
253
  hs?.port.postMessage({ type: "reset", id: owner[1], reason: payload });
216
254
  hs?.conns.delete(owner[1]);
217
255
  hostConns.delete(c);
256
+ loopbackConns.delete(c);
218
257
  }
219
258
  }
220
259
  }
221
260
 
261
+ /** Answers to host processes' DNS queries, to their processes. */
262
+ function deliverHostDns() {
263
+ for (const [q, code, result, reason] of pod.take_host_dns()) {
264
+ const owner = hostQueries.get(q);
265
+ hostQueries.delete(q);
266
+ const hs = owner && hostSockets.get(owner[0]);
267
+ hs?.port.postMessage(code ? { type: "query", id: owner[1], code, ...(reason ? { reason } : {}) } : { type: "query", id: owner[1], result });
268
+ }
269
+ }
270
+
222
271
  /** Relay tokens come from the page (getToken() cannot cross to the Worker). */
223
272
  function requestToken() {
224
273
  const id = ++nextToken;
@@ -231,6 +280,19 @@ function requestToken() {
231
280
  });
232
281
  }
233
282
 
283
+ /**
284
+ * OPFS may not answer at all (T307: WebKit's storage of a site left inconsistent, its data deleted in part): the CA's
285
+ * load or save is given up after this long (resolves null), and the pod goes on with a CA of this boot's.
286
+ */
287
+ const CA_STORAGE_MS = 10000;
288
+ function withinCa(what, p) {
289
+ let timer;
290
+ return Promise.race([p, new Promise((resolve) => (timer = setTimeout(() => {
291
+ log("warn", `CA: OPFS did not answer (${what}) in ${CA_STORAGE_MS / 1000} s: this site's storage is not responding; the pod CA is this boot's only`);
292
+ resolve(null);
293
+ }, CA_STORAGE_MS)))]).finally(() => clearTimeout(timer));
294
+ }
295
+
234
296
  /** The CA (certificate + key) stays in this Worker: OPFS when a key name is given. */
235
297
  async function loadCa(name) {
236
298
  if (!name) return "";
@@ -310,6 +372,7 @@ async function pump(memory, fromEngine, toEngine) {
310
372
  const now = performance.now();
311
373
  const active = pod.poll(now);
312
374
  if (hostConns.size || hostListeners.size) deliverHostEvents();
375
+ if (hostQueries.size) deliverHostDns();
313
376
  const out = pod.take();
314
377
  for (const f of out) if (!tx.tryPush(f)) await tx.pushAsync(f);
315
378
  for (const [id, f] of pod.take_forwarded()) peers.get(id)?.postMessage(f, [f.buffer]);
@@ -335,9 +398,9 @@ async function onAttach(m) {
335
398
  await ready;
336
399
  set_logger((level, text) => log(level, text), m.logLevel ?? null);
337
400
  const network = m.network ?? {};
338
- const bundle = await loadCa(m.caKey);
339
- pod = new NetPod(network, bundle, requestToken, Date.now() / 1000);
340
- if (!bundle) await saveCa(m.caKey, pod.ca_bundle());
401
+ const bundle = await withinCa("load", loadCa(m.caKey));
402
+ pod = new NetPod(network, bundle ?? "", requestToken, Date.now() / 1000);
403
+ if (bundle === "") await withinCa("save", saveCa(m.caKey, pod.ca_bundle()));
341
404
  pod.set_notify(() => wake?.());
342
405
  setInterval(() => pod?.set_unix_time(Date.now() / 1000), 60_000);
343
406
  for (const p of pendingInbound.splice(0)) pod.open_inbound(p);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpodjs/net-worker",
3
- "version": "0.2.7",
3
+ "version": "0.3.1",
4
4
  "description": "Net Worker for webpod: the guest's gateway (webpod-net NetStack), browser egress and page connections",
5
5
  "keywords": [
6
6
  "webpod",