Skip to main content

nodejs/stdlib/
tls.rs

1//! Node `tls` module: real TLS over blocking `rustls` (`rustls::StreamOwned`
2//! wrapping a `std::net::TcpStream`).
3//!
4//! Threading model mirrors `net` (see `host::run_event_loop`): background threads
5//! only move raw bytes and post `IoTask` closures onto the host channel; every
6//! JS-visible effect (building the `TLSSocket`, emitting `secureConnect`/`data`/
7//! `end`/`close`, calling listeners) happens on the main thread when the loop runs
8//! the posted closure. Background closures NEVER capture a `Value` (the heap is a
9//! main-thread `thread_local`); they capture only `Send` data (`u64` ids, byte
10//! vectors, `TcpStream`s, channel senders) and look the emitter up by id inside
11//! the posted `IoTask`.
12//!
13//! Per TLS connection there is ONE owner thread that solely owns the
14//! `StreamOwned`. It reads with a short socket read-timeout (so a `WouldBlock`
15//! lets it loop) and drains an mpsc channel of `WriteCmd`s produced by the main
16//! thread (`socket.write`/`socket.end`). Because reads and writes share the one
17//! rustls `Connection`, keeping both on a single thread avoids splitting the
18//! stateful cipher across threads.
19
20use crate::host::{invoke, with_host, IoTask, JsObj};
21use fusevm::Value;
22use indexmap::IndexMap;
23use once_cell::sync::OnceCell;
24use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
25use rustls::{
26    ClientConfig, ClientConnection, ConnectionCommon, DigitallySignedStruct, RootCertStore,
27    ServerConfig, ServerConnection, SideData, SignatureScheme, StreamOwned,
28};
29use std::collections::HashMap;
30use std::io::{Read, Write};
31use std::net::TcpStream;
32use std::ops::{Deref, DerefMut};
33use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
34use std::sync::mpsc::{Receiver, Sender};
35use std::sync::Arc;
36
37/// `tls` module functions routed through `stdlib::call`.
38pub const MODULE_METHODS: &[&str] = &[
39    "connect",
40    "createServer",
41    "createSecureContext",
42    "checkServerIdentity",
43    "convertALPNProtocols",
44    "getCiphers",
45    "getCACertificates",
46    "setDefaultCACertificates",
47    "getCertificateCompressionAlgorithms",
48];
49
50/// The standard OpenSSL cipher-suite names (lowercase) reported by
51/// `tls.getCiphers()`, matching Node v26's fixed list (TLS 1.2 suites plus the
52/// `tls_*` TLS 1.3 suites). A fixed protocol constant, not a runtime value.
53const CIPHERS: &[&str] = &[
54    "aes128-gcm-sha256",
55    "aes128-sha",
56    "aes128-sha256",
57    "aes256-gcm-sha384",
58    "aes256-sha",
59    "aes256-sha256",
60    "dhe-psk-aes128-cbc-sha",
61    "dhe-psk-aes128-cbc-sha256",
62    "dhe-psk-aes128-gcm-sha256",
63    "dhe-psk-aes256-cbc-sha",
64    "dhe-psk-aes256-cbc-sha384",
65    "dhe-psk-aes256-gcm-sha384",
66    "dhe-psk-chacha20-poly1305",
67    "dhe-rsa-aes128-gcm-sha256",
68    "dhe-rsa-aes128-sha",
69    "dhe-rsa-aes128-sha256",
70    "dhe-rsa-aes256-gcm-sha384",
71    "dhe-rsa-aes256-sha",
72    "dhe-rsa-aes256-sha256",
73    "dhe-rsa-chacha20-poly1305",
74    "ecdhe-ecdsa-aes128-gcm-sha256",
75    "ecdhe-ecdsa-aes128-sha",
76    "ecdhe-ecdsa-aes128-sha256",
77    "ecdhe-ecdsa-aes256-gcm-sha384",
78    "ecdhe-ecdsa-aes256-sha",
79    "ecdhe-ecdsa-aes256-sha384",
80    "ecdhe-ecdsa-chacha20-poly1305",
81    "ecdhe-psk-aes128-cbc-sha",
82    "ecdhe-psk-aes128-cbc-sha256",
83    "ecdhe-psk-aes256-cbc-sha",
84    "ecdhe-psk-aes256-cbc-sha384",
85    "ecdhe-psk-chacha20-poly1305",
86    "ecdhe-rsa-aes128-gcm-sha256",
87    "ecdhe-rsa-aes128-sha",
88    "ecdhe-rsa-aes128-sha256",
89    "ecdhe-rsa-aes256-gcm-sha384",
90    "ecdhe-rsa-aes256-sha",
91    "ecdhe-rsa-aes256-sha384",
92    "ecdhe-rsa-chacha20-poly1305",
93    "psk-aes128-cbc-sha",
94    "psk-aes128-cbc-sha256",
95    "psk-aes128-gcm-sha256",
96    "psk-aes256-cbc-sha",
97    "psk-aes256-cbc-sha384",
98    "psk-aes256-gcm-sha384",
99    "psk-chacha20-poly1305",
100    "rsa-psk-aes128-cbc-sha",
101    "rsa-psk-aes128-cbc-sha256",
102    "rsa-psk-aes128-gcm-sha256",
103    "rsa-psk-aes256-cbc-sha",
104    "rsa-psk-aes256-cbc-sha384",
105    "rsa-psk-aes256-gcm-sha384",
106    "rsa-psk-chacha20-poly1305",
107    "srp-aes-128-cbc-sha",
108    "srp-aes-256-cbc-sha",
109    "srp-rsa-aes-128-cbc-sha",
110    "srp-rsa-aes-256-cbc-sha",
111    "tls_aes_128_ccm_8_sha256",
112    "tls_aes_128_ccm_sha256",
113    "tls_aes_128_gcm_sha256",
114    "tls_aes_256_gcm_sha384",
115    "tls_chacha20_poly1305_sha256",
116];
117
118/// Instance method names for the two `@@native` tags this module owns, exposed to
119/// `stdlib::instance_has_method` (property reads that yield a bound method).
120pub const SERVER_METHODS: &[&str] = &["listen", "close", "address"];
121pub const SOCKET_METHODS: &[&str] = &[
122    "write",
123    "end",
124    "destroy",
125    "setEncoding",
126    "setKeepAlive",
127    "setNoDelay",
128    "setTimeout",
129    "ref",
130    "unref",
131    "pause",
132    "resume",
133];
134
135/// A native-thread hook run on the main thread for each freshly-handshaked
136/// connection. Set by `https` to attach its request parser; `None` for a plain
137/// `tls` server (which emits `secureConnect`/`connection` and calls its listener).
138pub type ConnHook = std::rc::Rc<dyn Fn(&Value, &Value, u64) -> Result<(), String>>;
139
140/// A write request handed from the main thread to a socket's owner thread.
141enum WriteCmd {
142    Data(Vec<u8>),
143    Shutdown,
144}
145
146/// Process-global monotonic id source for TLS sockets. Unlike `net`, ids are
147/// generated on background owner threads (before their main-thread record
148/// exists), so a lock-free atomic is used instead of a main-thread counter.
149static NEXT_TLS_ID: AtomicU64 = AtomicU64::new(1);
150static NEXT_SERVER_ID: AtomicU64 = AtomicU64::new(1);
151
152fn next_tls_id() -> u64 {
153    NEXT_TLS_ID.fetch_add(1, Ordering::Relaxed)
154}
155fn next_server_id() -> u64 {
156    NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed)
157}
158
159/// Main-thread record for a listening TLS server.
160struct TlsServerRec {
161    emitter: Value,
162    stop: Arc<AtomicBool>,
163    conn_hook: Option<ConnHook>,
164    /// Optional JS `connectionListener` (`(socket) => …`) for a plain tls server.
165    listener: Option<Value>,
166}
167
168/// Main-thread record for a live TLS socket.
169struct TlsSocketRec {
170    emitter: Value,
171    /// Queue of writes for the socket's owner thread.
172    tx: Sender<WriteCmd>,
173}
174
175#[derive(Default)]
176struct TlsState {
177    servers: HashMap<u64, TlsServerRec>,
178    sockets: HashMap<u64, TlsSocketRec>,
179}
180
181thread_local! {
182    static TLS: std::cell::RefCell<TlsState> = std::cell::RefCell::new(TlsState::default());
183    /// `ServerConfig`s built by `createServer` before `listen` assigns a server id
184    /// (mirrors `net::PENDING_HOOKS`).
185    static PENDING_CONFIGS: std::cell::RefCell<Vec<(Value, Arc<ServerConfig>)>> =
186        const { std::cell::RefCell::new(Vec::new()) };
187    static PENDING_HOOKS: std::cell::RefCell<Vec<(Value, ConnHook)>> =
188        const { std::cell::RefCell::new(Vec::new()) };
189    /// User-supplied default CA certificates (PEM strings) set via
190    /// `setDefaultCACertificates`; read back by `getCACertificates('default')`.
191    static DEFAULT_CA_CERTS: std::cell::RefCell<Vec<String>> =
192        const { std::cell::RefCell::new(Vec::new()) };
193}
194
195// ── shared object / prop helpers (same shape as net) ─────────────────────────
196
197fn get_prop(recv: &Value, key: &str) -> Option<Value> {
198    with_host(|h| match h.get(recv) {
199        Some(JsObj::Object(p)) => p.get(key).cloned(),
200        _ => None,
201    })
202}
203
204fn set_prop(recv: &Value, key: &str, val: Value) {
205    with_host(|h| {
206        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
207            p.insert(key.to_string(), val);
208        }
209    });
210}
211
212fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
213    get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
214}
215
216/// Delegate the EventEmitter surface to `events`; `None` for a non-emitter method.
217fn emitter_dispatch(recv: &Value, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
218    super::events::METHODS
219        .contains(&method)
220        .then(|| super::events::instance_call(recv, method, args.to_vec()))
221}
222
223/// Raw bytes of a `write`/`end` argument (Buffer bytes or a string's UTF-8),
224/// shared with the option-reading path for `key`/`cert` Buffers.
225fn value_bytes(v: Option<&Value>) -> Vec<u8> {
226    let Some(v) = v else { return Vec::new() };
227    let is_buffer =
228        with_host(|h| matches!(h.get(v), Some(JsObj::Object(p)) if p.contains_key("@@bytes")));
229    if is_buffer {
230        return with_host(|h| match h.get(v) {
231            Some(JsObj::Object(p)) => crate::stdlib::buffer::window_bytes_h(h, p),
232            _ => Vec::new(),
233        });
234    }
235    with_host(|h| h.str_of(v)).into_bytes()
236}
237
238// ── module entry ─────────────────────────────────────────────────────────────
239
240/// `stdlib::call` entry for `tls.<method>`.
241pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
242    match method {
243        "connect" => Some(connect(args)),
244        "createServer" => Some(create_server(args)),
245        // A secure context is just the parsed key/cert pair; we build the real
246        // `ServerConfig` lazily in `createServer`, so expose an opaque holder.
247        "createSecureContext" => Some(Ok(with_host(|h| {
248            let mut m = IndexMap::new();
249            m.insert("@@native".into(), h.new_str("SecureContext"));
250            if let Some(o) = args.first() {
251                m.insert("@@options".into(), o.clone());
252            }
253            h.new_object(m)
254        }))),
255        "checkServerIdentity" => Some(check_server_identity(args)),
256        "convertALPNProtocols" => Some(convert_alpn_protocols(args)),
257        "getCiphers" => Some(Ok(with_host(|h| {
258            let items = CIPHERS.iter().map(|c| h.new_str(*c)).collect();
259            h.new_array(items)
260        }))),
261        "getCACertificates" => Some(get_ca_certificates(args)),
262        "setDefaultCACertificates" => Some(set_default_ca_certificates(args)),
263        // rustls' default configuration does not negotiate TLS certificate
264        // compression (RFC 8879), so no algorithm is actually supported. Node v26
265        // likewise returns `[]` here.
266        "getCertificateCompressionAlgorithms" => Some(Ok(with_host(|h| h.new_array(Vec::new())))),
267        _ => None,
268    }
269}
270
271// ── tls.checkServerIdentity / ALPN / CA certificates ─────────────────────────
272
273/// Read an array of strings (or a single string) from a value; Buffers/other
274/// element types are stringified. Empty when the value is absent or not iterable.
275fn read_string_array(v: Option<&Value>) -> Vec<String> {
276    let Some(v) = v else { return Vec::new() };
277    with_host(|h| match h.get(v) {
278        Some(JsObj::Array(items)) => items.iter().map(|x| h.str_of(x)).collect(),
279        _ if h.as_str(v).is_some() => vec![h.str_of(v)],
280        _ => Vec::new(),
281    })
282}
283
284/// Does `host` match the certificate identity `pattern`, honouring a single
285/// leftmost-label wildcard (`*.example.com` matches `a.example.com` but not
286/// `example.com` nor `a.b.example.com`)? Case-insensitive.
287fn host_matches(host: &str, pattern: &str) -> bool {
288    let host = host.trim().to_ascii_lowercase();
289    let pattern = pattern.trim().to_ascii_lowercase();
290    if let Some(suffix) = pattern.strip_prefix("*.") {
291        // Wildcard covers exactly one leftmost label.
292        match host.split_once('.') {
293            Some((_, rest)) => rest == suffix,
294            None => false,
295        }
296    } else {
297        host == pattern
298    }
299}
300
301/// `tls.checkServerIdentity(hostname, cert)` — best-effort string comparison of
302/// `hostname` against the certificate's `subjectaltname` DNS entries (falling
303/// back to `subject.CN` when no SAN is present). Returns `undefined` on a match,
304/// or an `ERR_TLS_CERT_ALTNAME_INVALID`-shaped Error object on mismatch.
305fn check_server_identity(args: &[Value]) -> Result<Value, String> {
306    let host = super::arg_str(args, 0);
307    let cert = args.get(1).cloned().unwrap_or(Value::Undef);
308
309    // Collect DNS altnames from `subjectaltname` ("DNS:a.com, DNS:*.b.com").
310    let altname_str = get_prop(&cert, "subjectaltname")
311        .filter(|v| with_host(|h| h.as_str(v)).is_some())
312        .map(|v| with_host(|h| h.str_of(&v)))
313        .unwrap_or_default();
314    let dns_names: Vec<String> = altname_str
315        .split(',')
316        .filter_map(|e| e.trim().strip_prefix("DNS:").map(|s| s.trim().to_string()))
317        .filter(|s| !s.is_empty())
318        .collect();
319
320    let matched = if !dns_names.is_empty() {
321        dns_names.iter().any(|p| host_matches(&host, p))
322    } else {
323        // No SAN: fall back to the subject Common Name.
324        let cn = get_prop(&cert, "subject")
325            .and_then(|s| get_prop(&s, "CN"))
326            .filter(|v| with_host(|h| h.as_str(v)).is_some())
327            .map(|v| with_host(|h| h.str_of(&v)))
328            .unwrap_or_default();
329        !cn.is_empty() && host_matches(&host, &cn)
330    };
331
332    if matched {
333        return Ok(Value::Undef);
334    }
335    let reason = if !altname_str.is_empty() {
336        format!("Host: {host}. is not in the cert's altnames: {altname_str}")
337    } else {
338        format!("Host: {host}. is not cert's CN")
339    };
340    let message = format!("Hostname/IP does not match certificate's altnames: {reason}");
341    Ok(with_host(|h| {
342        let mut m = IndexMap::new();
343        m.insert("message".into(), h.new_str(message));
344        m.insert("reason".into(), h.new_str(reason));
345        m.insert("host".into(), h.new_str(host));
346        m.insert("code".into(), h.new_str("ERR_TLS_CERT_ALTNAME_INVALID"));
347        m.insert("cert".into(), cert);
348        h.new_object(m)
349    }))
350}
351
352/// `tls.convertALPNProtocols(protocols, out)` — encode `protocols` into the wire
353/// format (each entry prefixed by a single length byte), store it on
354/// `out.ALPNProtocols` as a Buffer, and return that Buffer.
355fn convert_alpn_protocols(args: &[Value]) -> Result<Value, String> {
356    let protocols = read_string_array(args.first());
357    let mut wire = Vec::new();
358    for p in &protocols {
359        let bytes = p.as_bytes();
360        // Node clamps to 255 (a single length byte); over-long entries throw, but
361        // best-effort here simply truncates the encoded length.
362        wire.push(bytes.len().min(255) as u8);
363        wire.extend_from_slice(&bytes[..bytes.len().min(255)]);
364    }
365    let buf = super::buffer::from_bytes(&wire);
366    if let Some(out) = args.get(1).filter(|v| matches!(v, Value::Obj(_))) {
367        set_prop(out, "ALPNProtocols", buf.clone());
368    }
369    Ok(buf)
370}
371
372/// node's bundled Mozilla root store (`src/node_root_certs.h` of the reference
373/// release, transcribed by `scripts/gen_root_certs.pl`), one PEM block each.
374const ROOT_CERTS_PEM: &str = include_str!("root_certs.pem");
375
376/// The bundled root certificates as PEM strings, in node's order, each from
377/// `-----BEGIN CERTIFICATE-----` to `-----END CERTIFICATE-----`.
378fn bundled_root_pems() -> impl Iterator<Item = &'static str> {
379    const END: &str = "-----END CERTIFICATE-----";
380    ROOT_CERTS_PEM
381        .split_inclusive(END)
382        .map(str::trim_start)
383        .filter(|c| c.ends_with(END))
384}
385
386/// A frozen array of `certs` (`ObjectFreeze`, as node's caches are).
387fn frozen_strings<'a>(certs: impl Iterator<Item = &'a str>) -> Value {
388    with_host(|h| {
389        let items = certs.map(|c| h.new_str(c.to_string())).collect();
390        let arr = h.new_array(items);
391        h.seal_object(&arr, true);
392        arr
393    })
394}
395
396/// The data exports of `tls` (`lib/tls.js`). `rootCertificates` is the
397/// `cacheBundledRootCertificates` getter's value, built once by the caller.
398pub fn constant(name: &str) -> Option<Value> {
399    Some(match name {
400        "rootCertificates" => frozen_strings(bundled_root_pems()),
401        "DEFAULT_MIN_VERSION" => with_host(|h| h.new_str("TLSv1.2")),
402        "DEFAULT_MAX_VERSION" => with_host(|h| h.new_str("TLSv1.3")),
403        "DEFAULT_ECDH_CURVE" => with_host(|h| h.new_str("auto")),
404        "DEFAULT_CIPHERS" => with_host(|h| h.new_str(DEFAULT_CIPHERS)),
405        "CLIENT_RENEG_LIMIT" => Value::Float(3.0),
406        "CLIENT_RENEG_WINDOW" => Value::Float(600.0),
407        _ => return None,
408    })
409}
410
411/// `tls.DEFAULT_CIPHERS`: node's default cipher list (`--tls-cipher-list`
412/// unset), the TLS 1.3 suites followed by the OpenSSL 1.2 selection.
413const DEFAULT_CIPHERS: &str = "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:\
414TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:\
415ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:\
416ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:\
417DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:\
418!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA";
419
420/// `tls.getCACertificates([type])` (`lib/tls.js`): `'bundled'` is
421/// `tls.rootCertificates`; `'default'` is the set `setDefaultCACertificates`
422/// installed, else a frozen copy of the bundled store (node adds
423/// `NODE_EXTRA_CA_CERTS` to it, which is not read here); `'extra'` and
424/// `'system'` are empty — this runtime reads neither the extra-certs file nor
425/// the OS store. Any other type is `ERR_INVALID_ARG_VALUE`.
426fn get_ca_certificates(args: &[Value]) -> Result<Value, String> {
427    thread_local! {
428        static DEFAULT: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
429    }
430    let kind = if args.is_empty() || matches!(args[0], Value::Undef) {
431        "default".to_string()
432    } else {
433        super::arg_str(args, 0)
434    };
435    match kind.as_str() {
436        "bundled" => Ok(super::constant("tls", "rootCertificates").unwrap_or(Value::Undef)),
437        "default" => {
438            let set = DEFAULT_CA_CERTS.with(|c| c.borrow().clone());
439            if !set.is_empty() {
440                return Ok(frozen_strings(set.iter().map(String::as_str)));
441            }
442            if let Some(v) = DEFAULT.with(|d| d.borrow().clone()) {
443                return Ok(v);
444            }
445            let v = frozen_strings(bundled_root_pems());
446            DEFAULT.with(|d| *d.borrow_mut() = Some(v.clone()));
447            Ok(v)
448        }
449        "system" | "extra" => Ok(frozen_strings(std::iter::empty())),
450        _ => Err(crate::host::coded_error(
451            "TypeError",
452            "ERR_INVALID_ARG_VALUE",
453            &format!(
454                "The argument 'type' is invalid. Received {}",
455                with_host(|h| h.inspect(&args[0]))
456            ),
457        )),
458    }
459}
460
461/// `tls.setDefaultCACertificates(certs)` — store `certs` (PEM strings or Buffers)
462/// as the process default CA set for later `getCACertificates('default')` reads.
463fn set_default_ca_certificates(args: &[Value]) -> Result<Value, String> {
464    let certs = read_string_array(args.first());
465    DEFAULT_CA_CERTS.with(|c| *c.borrow_mut() = certs);
466    Ok(Value::Undef)
467}
468
469// ── TLS crypto config ────────────────────────────────────────────────────────
470
471/// The shared verifying client config (explicit aws-lc-rs crypto provider +
472/// webpki-roots trust anchors). Built once. Uses `builder_with_provider` rather
473/// than `builder()` so it never depends on a process-default provider being
474/// pre-installed (the insecure path installs none).
475fn verifying_client_config() -> Arc<ClientConfig> {
476    static CFG: OnceCell<Arc<ClientConfig>> = OnceCell::new();
477    CFG.get_or_init(|| {
478        let root_store = RootCertStore {
479            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
480        };
481        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
482        let cfg = ClientConfig::builder_with_provider(provider)
483            .with_safe_default_protocol_versions()
484            .expect("aws-lc-rs provider supports the default protocol versions")
485            .with_root_certificates(root_store)
486            .with_no_client_auth();
487        Arc::new(cfg)
488    })
489    .clone()
490}
491
492/// A client config that accepts any server certificate (`rejectUnauthorized:
493/// false`). Signature verification is still delegated to the default provider's
494/// algorithms; only chain-to-a-trust-anchor and hostname checks are skipped.
495fn insecure_client_config() -> Arc<ClientConfig> {
496    static CFG: OnceCell<Arc<ClientConfig>> = OnceCell::new();
497    CFG.get_or_init(|| {
498        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
499        let cfg = ClientConfig::builder_with_provider(provider.clone())
500            .with_safe_default_protocol_versions()
501            .expect("aws-lc-rs provider supports the default protocol versions")
502            .dangerous()
503            .with_custom_certificate_verifier(Arc::new(NoVerify(provider)))
504            .with_no_client_auth();
505        Arc::new(cfg)
506    })
507    .clone()
508}
509
510/// A `ServerCertVerifier` that skips certificate-chain/hostname validation but
511/// still checks the handshake signature against the default provider's algorithms.
512#[derive(Debug)]
513struct NoVerify(Arc<rustls::crypto::CryptoProvider>);
514
515impl rustls::client::danger::ServerCertVerifier for NoVerify {
516    fn verify_server_cert(
517        &self,
518        _end_entity: &CertificateDer<'_>,
519        _intermediates: &[CertificateDer<'_>],
520        _server_name: &ServerName<'_>,
521        _ocsp: &[u8],
522        _now: UnixTime,
523    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
524        Ok(rustls::client::danger::ServerCertVerified::assertion())
525    }
526    fn verify_tls12_signature(
527        &self,
528        message: &[u8],
529        cert: &CertificateDer<'_>,
530        dss: &DigitallySignedStruct,
531    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
532        rustls::crypto::verify_tls12_signature(
533            message,
534            cert,
535            dss,
536            &self.0.signature_verification_algorithms,
537        )
538    }
539    fn verify_tls13_signature(
540        &self,
541        message: &[u8],
542        cert: &CertificateDer<'_>,
543        dss: &DigitallySignedStruct,
544    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
545        rustls::crypto::verify_tls13_signature(
546            message,
547            cert,
548            dss,
549            &self.0.signature_verification_algorithms,
550        )
551    }
552    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
553        self.0.signature_verification_algorithms.supported_schemes()
554    }
555}
556
557/// The shared client `ClientConfig` for a given `rejectUnauthorized` setting.
558/// Public so the `https` client (`https.request`/`https.get`) reuses the same
559/// trust configuration as `tls.connect`.
560pub fn client_config(reject_unauthorized: bool) -> Arc<ClientConfig> {
561    if reject_unauthorized {
562        verifying_client_config()
563    } else {
564        insecure_client_config()
565    }
566}
567
568/// Build a `ServerConfig` from PEM `key`+`cert` bytes.
569pub fn build_server_config(cert_pem: &[u8], key_pem: &[u8]) -> Result<Arc<ServerConfig>, String> {
570    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut &cert_pem[..])
571        .collect::<Result<_, _>>()
572        .map_err(|e| format!("Error: tls: bad certificate PEM: {e}"))?;
573    if certs.is_empty() {
574        return Err("Error: tls: no certificates found in `cert`".to_string());
575    }
576    let key: PrivateKeyDer<'static> = rustls_pemfile::private_key(&mut &key_pem[..])
577        .map_err(|e| format!("Error: tls: bad private key PEM: {e}"))?
578        .ok_or_else(|| "Error: tls: no private key found in `key`".to_string())?;
579    let cfg = ServerConfig::builder()
580        .with_no_client_auth()
581        .with_single_cert(certs, key)
582        .map_err(|e| format!("Error: tls: invalid key/cert: {e}"))?;
583    Ok(Arc::new(cfg))
584}
585
586// ── tls.connect (client) ─────────────────────────────────────────────────────
587
588/// `tls.connect(options[, cb])` / `tls.connect(port[, host][, options][, cb])`.
589/// Returns a `TLSSocket` immediately; the TCP connect + handshake run on a
590/// background thread and emit `secureConnect` (or `error`) when complete.
591pub fn connect(args: &[Value]) -> Result<Value, String> {
592    let mut port: u16 = 0;
593    let mut host = "localhost".to_string();
594    let mut servername: Option<String> = None;
595    let mut reject_unauthorized = true;
596    let mut cb: Option<Value> = None;
597
598    for a in args {
599        let n = with_host(|h| h.to_number(a));
600        if with_host(|h| crate::host::is_callable(h, a)) {
601            cb = Some(a.clone());
602        } else if !n.is_nan() && matches!(a, Value::Float(_) | Value::Int(_)) {
603            port = n as u16;
604        } else if with_host(|h| h.as_str(a)).is_some() {
605            host = with_host(|h| h.str_of(a));
606        } else if matches!(a, Value::Obj(_)) {
607            // Options object.
608            if let Some(p) = get_prop(a, "port") {
609                port = with_host(|h| h.to_number(&p)) as u16;
610            }
611            for key in ["host", "hostname"] {
612                if let Some(hv) = get_prop(a, key).filter(|v| with_host(|h| h.as_str(v)).is_some())
613                {
614                    host = with_host(|h| h.str_of(&hv));
615                }
616            }
617            if let Some(sv) =
618                get_prop(a, "servername").filter(|v| with_host(|h| h.as_str(v)).is_some())
619            {
620                servername = Some(with_host(|h| h.str_of(&sv)));
621            }
622            if let Some(rv) = get_prop(a, "rejectUnauthorized") {
623                reject_unauthorized = with_host(|h| h.truthy(&rv));
624            }
625        }
626    }
627    let servername = servername.unwrap_or_else(|| host.clone());
628
629    // Build the socket object + register its write channel on the main thread.
630    let sock_id = next_tls_id();
631    let (tx, rx) = std::sync::mpsc::channel::<WriteCmd>();
632    let mut extra = IndexMap::new();
633    extra.insert("@@tlsid".into(), Value::Float(sock_id as f64));
634    extra.insert("authorized".into(), Value::Bool(reject_unauthorized));
635    extra.insert("encrypted".into(), Value::Bool(true));
636    let socket = new_emitter_object("TLSSocket", extra);
637    TLS.with(|s| {
638        s.borrow_mut().sockets.insert(
639            sock_id,
640            TlsSocketRec {
641                emitter: socket.clone(),
642                tx,
643            },
644        );
645    });
646    with_host(|h| h.incr_handle());
647    // `tls.connect(opts, cb)` registers `cb` as a one-shot `secureConnect` listener.
648    if let Some(cb) = cb {
649        super::events::instance_call(
650            &socket,
651            "once",
652            vec![with_host(|h| h.new_str("secureConnect")), cb],
653        )?;
654    }
655
656    let io_tx = with_host(|h| h.io_sender());
657    let config = if reject_unauthorized {
658        verifying_client_config()
659    } else {
660        insecure_client_config()
661    };
662
663    std::thread::spawn(move || {
664        let server_name = match ServerName::try_from(servername.clone()) {
665            Ok(n) => n,
666            Err(_) => {
667                post_socket_error(
668                    &io_tx,
669                    sock_id,
670                    format!("Error: tls: invalid servername '{servername}'"),
671                );
672                return;
673            }
674        };
675        let mut sock = match TcpStream::connect((host.as_str(), port)) {
676            Ok(s) => s,
677            Err(e) => {
678                post_socket_error(
679                    &io_tx,
680                    sock_id,
681                    format!("Error: connect ECONNREFUSED {host}:{port}: {e}"),
682                );
683                return;
684            }
685        };
686        let mut conn = match ClientConnection::new(config, server_name) {
687            Ok(c) => c,
688            Err(e) => {
689                post_socket_error(&io_tx, sock_id, format!("Error: tls: {e}"));
690                return;
691            }
692        };
693        // Drive the handshake to completion (blocking).
694        if let Err(e) = conn.complete_io(&mut sock) {
695            post_socket_error(&io_tx, sock_id, format!("Error: tls handshake failed: {e}"));
696            return;
697        }
698        let _ = io_tx.send(Box::new(move || on_secure_connect(sock_id)));
699        let stream = StreamOwned::new(conn, sock);
700        owner_loop(stream, sock_id, rx, io_tx);
701    });
702
703    Ok(socket)
704}
705
706/// Emit `secureConnect` on a freshly-handshaked socket (runs on the main thread).
707fn on_secure_connect(sock_id: u64) -> Result<(), String> {
708    let socket = TLS.with(|s| s.borrow().sockets.get(&sock_id).map(|r| r.emitter.clone()));
709    if let Some(socket) = socket {
710        super::events::instance_call(
711            &socket,
712            "emit",
713            vec![with_host(|h| h.new_str("secureConnect"))],
714        )?;
715    }
716    Ok(())
717}
718
719/// Post an `error` event (then close) for a socket whose connect/handshake failed.
720fn post_socket_error(io_tx: &Sender<IoTask>, sock_id: u64, msg: String) {
721    let _ = io_tx.send(Box::new(move || {
722        let socket = TLS.with(|s| s.borrow().sockets.get(&sock_id).map(|r| r.emitter.clone()));
723        if let Some(socket) = socket {
724            let err = with_host(|h| {
725                let mut m = IndexMap::new();
726                m.insert("message".into(), h.new_str(msg.clone()));
727                h.new_object(m)
728            });
729            super::events::instance_call(
730                &socket,
731                "emit",
732                vec![with_host(|h| h.new_str("error")), err],
733            )?;
734        }
735        on_socket_close(sock_id)
736    }));
737}
738
739// ── tls.createServer ─────────────────────────────────────────────────────────
740
741/// `tls.createServer([options][, secureConnectionListener])`. Parses `key`+`cert`
742/// into a `ServerConfig` eagerly (so a bad cert throws synchronously) and returns
743/// a `TLSServer` emitter.
744pub fn create_server(args: &[Value]) -> Result<Value, String> {
745    let mut options: Option<Value> = None;
746    let mut listener: Option<Value> = None;
747    for a in args {
748        if with_host(|h| crate::host::is_callable(h, a)) {
749            listener = Some(a.clone());
750        } else if matches!(a, Value::Obj(_)) {
751            options = Some(a.clone());
752        }
753    }
754    let opts = options.ok_or_else(|| {
755        crate::host::type_error("tls.createServer requires an options object with `key` and `cert`")
756    })?;
757    let cert = value_bytes(get_prop(&opts, "cert").as_ref());
758    let key = value_bytes(get_prop(&opts, "key").as_ref());
759    if cert.is_empty() || key.is_empty() {
760        return Err(crate::host::type_error(
761            "tls.createServer requires `key` and `cert`",
762        ));
763    }
764    let config = build_server_config(&cert, &key)?;
765
766    let mut extra = IndexMap::new();
767    if let Some(cb) = listener {
768        extra.insert("@@connListener".into(), cb);
769    }
770    let server = new_emitter_object("TLSServer", extra);
771    PENDING_CONFIGS.with(|p| p.borrow_mut().push((server.clone(), config)));
772    Ok(server)
773}
774
775/// Build a TLS server backed by a caller-supplied per-connection hook (used by
776/// `https::create_server`). Returns the `TLSServer` emitter; the caller stores its
777/// `requestListener` and registers the hook.
778pub fn create_server_with_config(
779    config: Arc<ServerConfig>,
780    hook: ConnHook,
781    request_listener: Value,
782) -> Value {
783    let mut extra = IndexMap::new();
784    extra.insert("@@requestListener".into(), request_listener);
785    let server = new_emitter_object("TLSServer", extra);
786    PENDING_CONFIGS.with(|p| p.borrow_mut().push((server.clone(), config)));
787    PENDING_HOOKS.with(|p| p.borrow_mut().push((server.clone(), hook)));
788    server
789}
790
791fn take_pending_config(server: &Value) -> Option<Arc<ServerConfig>> {
792    PENDING_CONFIGS.with(|p| {
793        let mut p = p.borrow_mut();
794        p.iter()
795            .position(|(s, _)| s == server)
796            .map(|pos| p.remove(pos).1)
797    })
798}
799fn take_pending_hook(server: &Value) -> Option<ConnHook> {
800    PENDING_HOOKS.with(|p| {
801        let mut p = p.borrow_mut();
802        p.iter()
803            .position(|(s, _)| s == server)
804            .map(|pos| p.remove(pos).1)
805    })
806}
807
808// ── instance dispatch (TLSServer / TLSSocket) ────────────────────────────────
809
810pub fn instance_call(
811    tag: &str,
812    recv: &Value,
813    method: &str,
814    args: Vec<Value>,
815) -> Result<Value, String> {
816    match tag {
817        "TLSServer" => server_call(recv, method, args),
818        "TLSSocket" => socket_call(recv, method, args),
819        _ => Err(crate::host::type_error(&format!(
820            "{method} is not a function"
821        ))),
822    }
823}
824
825fn server_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
826    if let Some(r) = emitter_dispatch(recv, method, &args) {
827        return r;
828    }
829    match method {
830        "listen" => server_listen(recv, &args),
831        "close" => server_close(recv, &args),
832        "address" => Ok(get_prop(recv, "@@address").unwrap_or(Value::Undef)),
833        _ => Err(crate::host::type_error(&format!(
834            "server.{method} is not a function"
835        ))),
836    }
837}
838
839/// `server.listen(port[, host][, callback])`. Binds on the main thread, spawns the
840/// accept loop, and fires `listening` + callback asynchronously.
841fn server_listen(recv: &Value, args: &[Value]) -> Result<Value, String> {
842    let port = with_host(|h| args.first().map(|v| h.to_number(v)).unwrap_or(0.0)) as u16;
843    let mut host = "0.0.0.0".to_string();
844    let mut cb: Option<Value> = None;
845    for a in &args[1.min(args.len())..] {
846        if with_host(|h| h.as_str(a)).is_some() {
847            host = with_host(|h| h.str_of(a));
848        } else if with_host(|h| crate::host::is_callable(h, a)) {
849            cb = Some(a.clone());
850        }
851    }
852
853    let config = take_pending_config(recv)
854        .ok_or_else(|| crate::host::type_error("tls server has no secure context"))?;
855    let listener = std::net::TcpListener::bind((host.as_str(), port))
856        .map_err(|e| format!("Error: listen EADDRINUSE: {e}"))?;
857    let local = listener.local_addr().ok();
858
859    let id = next_server_id();
860    set_prop(recv, "@@serverid", Value::Float(id as f64));
861    if let Some(addr) = local {
862        let mut a = IndexMap::new();
863        a.insert("port".into(), Value::Float(addr.port() as f64));
864        a.insert(
865            "address".into(),
866            with_host(|h| h.new_str(addr.ip().to_string())),
867        );
868        a.insert(
869            "family".into(),
870            with_host(|h| h.new_str(if addr.is_ipv6() { "IPv6" } else { "IPv4" })),
871        );
872        let addr_obj = with_host(|h| h.new_object(a));
873        set_prop(recv, "@@address", addr_obj);
874    }
875    let conn_hook = take_pending_hook(recv);
876    let request_listener = get_prop(recv, "@@requestListener");
877    let plain_listener = get_prop(recv, "@@connListener");
878    let stop = Arc::new(AtomicBool::new(false));
879    TLS.with(|s| {
880        s.borrow_mut().servers.insert(
881            id,
882            TlsServerRec {
883                emitter: recv.clone(),
884                stop: stop.clone(),
885                conn_hook,
886                listener: plain_listener,
887            },
888        );
889    });
890    // Preserve the https request listener where the hook can find it (already on
891    // the object as `@@requestListener`); nothing else to stash.
892    let _ = request_listener;
893    with_host(|h| h.incr_handle());
894
895    let io_tx = with_host(|h| h.io_sender());
896    listener.set_nonblocking(true).ok();
897    std::thread::spawn(move || {
898        loop {
899            if stop.load(Ordering::Acquire) {
900                break;
901            }
902            match listener.accept() {
903                Ok((stream, _addr)) => {
904                    let cfg = config.clone();
905                    let tx = io_tx.clone();
906                    // One handshake+owner thread per connection.
907                    std::thread::spawn(move || accept_connection(id, stream, cfg, tx));
908                }
909                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
910                    std::thread::sleep(std::time::Duration::from_millis(5));
911                }
912                Err(_) => break,
913            }
914        }
915    });
916
917    let server = recv.clone();
918    let _ = with_host(|h| h.io_sender()).send(Box::new(move || {
919        super::events::instance_call(&server, "emit", vec![with_host(|h| h.new_str("listening"))])?;
920        if let Some(cb) = cb {
921            invoke(&cb, Vec::new(), None)?;
922        }
923        Ok(())
924    }));
925    Ok(recv.clone())
926}
927
928/// A background per-connection thread: complete the server handshake, then post an
929/// `IoTask` that surfaces the socket to JS, and finally become its owner loop.
930fn accept_connection(
931    server_id: u64,
932    mut sock: TcpStream,
933    config: Arc<ServerConfig>,
934    io_tx: Sender<IoTask>,
935) {
936    // The socket is inherited non-blocking from the accept poll loop; put it in
937    // blocking mode so the TLS handshake below can't fail with WouldBlock. The
938    // `http2` server does the same for the same reason; without it every
939    // handshake aborted on BSD, where an accepted socket inherits the
940    // listener's O_NONBLOCK, and the peer saw `unexpected end of file`.
941    sock.set_nonblocking(false).ok();
942    let mut conn = match ServerConnection::new(config) {
943        Ok(c) => c,
944        Err(_) => return,
945    };
946    if conn.complete_io(&mut sock).is_err() {
947        return;
948    }
949    let sock_id = next_tls_id();
950    let (tx, rx) = std::sync::mpsc::channel::<WriteCmd>();
951    let tx_for_main = tx;
952    let _ = io_tx.send(Box::new(move || {
953        on_server_connection(server_id, sock_id, tx_for_main)
954    }));
955    let stream = StreamOwned::new(conn, sock);
956    owner_loop(stream, sock_id, rx, io_tx);
957}
958
959/// Main-thread handler for a newly-handshaked server connection: build the
960/// `TLSSocket`, register it, run the server's hook/listener, emit events.
961fn on_server_connection(server_id: u64, sock_id: u64, tx: Sender<WriteCmd>) -> Result<(), String> {
962    let server = TLS.with(|s| {
963        s.borrow()
964            .servers
965            .get(&server_id)
966            .map(|r| r.emitter.clone())
967    });
968    let Some(server) = server else { return Ok(()) };
969
970    let mut extra = IndexMap::new();
971    extra.insert("@@tlsid".into(), Value::Float(sock_id as f64));
972    extra.insert("encrypted".into(), Value::Bool(true));
973    let socket = new_emitter_object("TLSSocket", extra);
974    TLS.with(|s| {
975        s.borrow_mut().sockets.insert(
976            sock_id,
977            TlsSocketRec {
978                emitter: socket.clone(),
979                tx,
980            },
981        );
982    });
983    with_host(|h| h.incr_handle());
984
985    // `secureConnection` is the tls server event; also emit `connection` for parity.
986    super::events::instance_call(
987        &server,
988        "emit",
989        vec![with_host(|h| h.new_str("secureConnection")), socket.clone()],
990    )?;
991    super::events::instance_call(
992        &server,
993        "emit",
994        vec![with_host(|h| h.new_str("connection")), socket.clone()],
995    )?;
996
997    // https attaches a request-parser hook; a plain tls server runs its listener.
998    let hook = TLS.with(|s| {
999        s.borrow()
1000            .servers
1001            .get(&server_id)
1002            .and_then(|r| r.conn_hook.clone())
1003    });
1004    if let Some(hook) = hook {
1005        hook(&server, &socket, sock_id)?;
1006    } else {
1007        let listener = TLS.with(|s| {
1008            s.borrow()
1009                .servers
1010                .get(&server_id)
1011                .and_then(|r| r.listener.clone())
1012        });
1013        if let Some(cb) = listener {
1014            invoke(&cb, vec![socket.clone()], None)?;
1015        }
1016    }
1017    Ok(())
1018}
1019
1020fn server_close(recv: &Value, args: &[Value]) -> Result<Value, String> {
1021    if let Some(id) = u64_prop(recv, "@@serverid") {
1022        let rec = TLS.with(|s| s.borrow_mut().servers.remove(&id));
1023        if let Some(rec) = rec {
1024            rec.stop.store(true, Ordering::Release);
1025            with_host(|h| h.decr_handle());
1026            let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1027        }
1028    }
1029    if let Some(cb) = args
1030        .first()
1031        .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
1032    {
1033        invoke(cb, Vec::new(), None)?;
1034    }
1035    super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))])?;
1036    Ok(recv.clone())
1037}
1038
1039// ── TLSSocket instance methods ───────────────────────────────────────────────
1040
1041fn socket_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
1042    if let Some(r) = emitter_dispatch(recv, method, &args) {
1043        return r;
1044    }
1045    match method {
1046        "write" => {
1047            if let Some(id) = u64_prop(recv, "@@tlsid") {
1048                socket_write(id, &value_bytes(args.first()));
1049            }
1050            Ok(Value::Bool(true))
1051        }
1052        "end" => {
1053            if let Some(id) = u64_prop(recv, "@@tlsid") {
1054                if let Some(chunk) = args.first().filter(|v| !matches!(v, Value::Undef)) {
1055                    socket_write(id, &value_bytes(Some(chunk)));
1056                }
1057                socket_end(id);
1058            }
1059            Ok(recv.clone())
1060        }
1061        "destroy" => {
1062            if let Some(id) = u64_prop(recv, "@@tlsid") {
1063                socket_end(id);
1064            }
1065            Ok(recv.clone())
1066        }
1067        "setEncoding" | "setTimeout" | "setNoDelay" | "setKeepAlive" | "ref" | "unref"
1068        | "pause" | "resume" => Ok(recv.clone()),
1069        _ => Err(crate::host::type_error(&format!(
1070            "socket.{method} is not a function"
1071        ))),
1072    }
1073}
1074
1075/// Queue plaintext to be written by the socket's owner thread (no-op if closed).
1076/// Public so `https` server responses can write through the TLS channel.
1077pub fn socket_write(sock_id: u64, data: &[u8]) {
1078    let tx = TLS.with(|s| s.borrow().sockets.get(&sock_id).map(|r| r.tx.clone()));
1079    if let Some(tx) = tx {
1080        let _ = tx.send(WriteCmd::Data(data.to_vec()));
1081    }
1082}
1083
1084/// Signal end-of-write (TLS close-notify + TCP write shutdown) on a socket.
1085pub fn socket_end(sock_id: u64) {
1086    let tx = TLS.with(|s| s.borrow().sockets.get(&sock_id).map(|r| r.tx.clone()));
1087    if let Some(tx) = tx {
1088        let _ = tx.send(WriteCmd::Shutdown);
1089    }
1090}
1091
1092// ── the per-socket owner thread ──────────────────────────────────────────────
1093
1094/// Sole owner of one connection's `StreamOwned`. Reads with a short socket
1095/// read-timeout (a `WouldBlock` just loops) and drains the write channel. Posts
1096/// `data`/`end`/`close` `IoTask`s to the main thread. Generic over client/server
1097/// connections (both deref to `ConnectionCommon`), mirroring `StreamOwned`'s
1098/// bounds.
1099fn owner_loop<C, S>(
1100    mut stream: StreamOwned<C, TcpStream>,
1101    sock_id: u64,
1102    rx: Receiver<WriteCmd>,
1103    io_tx: Sender<IoTask>,
1104) where
1105    C: DerefMut + Deref<Target = ConnectionCommon<S>>,
1106    S: SideData,
1107{
1108    stream
1109        .sock
1110        .set_read_timeout(Some(std::time::Duration::from_millis(20)))
1111        .ok();
1112    let mut buf = [0u8; 16384];
1113    loop {
1114        // 1) drain any queued writes.
1115        let mut shutdown = false;
1116        loop {
1117            match rx.try_recv() {
1118                Ok(WriteCmd::Data(bytes)) => {
1119                    if stream
1120                        .write_all(&bytes)
1121                        .and_then(|_| stream.flush())
1122                        .is_err()
1123                    {
1124                        let _ = io_tx.send(Box::new(move || on_socket_close(sock_id)));
1125                        return;
1126                    }
1127                }
1128                Ok(WriteCmd::Shutdown) => shutdown = true,
1129                Err(std::sync::mpsc::TryRecvError::Empty) => break,
1130                Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
1131            }
1132        }
1133        if shutdown {
1134            stream.conn.send_close_notify();
1135            let _ = stream.flush();
1136            let _ = stream.sock.shutdown(std::net::Shutdown::Write);
1137        }
1138
1139        // 2) read whatever plaintext is available.
1140        match stream.read(&mut buf) {
1141            Ok(0) => {
1142                let _ = io_tx.send(Box::new(move || on_socket_end(sock_id)));
1143                return;
1144            }
1145            Ok(n) => {
1146                let bytes = buf[..n].to_vec();
1147                let _ = io_tx.send(Box::new(move || on_socket_data(sock_id, bytes)));
1148            }
1149            Err(ref e)
1150                if matches!(
1151                    e.kind(),
1152                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
1153                ) =>
1154            {
1155                // No plaintext ready; loop to service writes again.
1156                continue;
1157            }
1158            Err(_) => {
1159                let _ = io_tx.send(Box::new(move || on_socket_close(sock_id)));
1160                return;
1161            }
1162        }
1163    }
1164}
1165
1166// ── main-thread socket event handlers (run from posted IoTasks) ──────────────
1167
1168fn on_socket_data(sock_id: u64, bytes: Vec<u8>) -> Result<(), String> {
1169    let socket = TLS.with(|s| s.borrow().sockets.get(&sock_id).map(|r| r.emitter.clone()));
1170    let Some(socket) = socket else { return Ok(()) };
1171    // Feed the https request parser first (no-op unless this is an https conn).
1172    super::https::feed(sock_id, &socket, &bytes)?;
1173    let chunk = super::buffer::from_bytes(&bytes);
1174    super::events::instance_call(
1175        &socket,
1176        "emit",
1177        vec![with_host(|h| h.new_str("data")), chunk],
1178    )?;
1179    Ok(())
1180}
1181
1182fn on_socket_end(sock_id: u64) -> Result<(), String> {
1183    let socket = TLS.with(|s| s.borrow().sockets.get(&sock_id).map(|r| r.emitter.clone()));
1184    if let Some(socket) = socket {
1185        super::events::instance_call(&socket, "emit", vec![with_host(|h| h.new_str("end"))])?;
1186    }
1187    on_socket_close(sock_id)
1188}
1189
1190fn on_socket_close(sock_id: u64) -> Result<(), String> {
1191    let rec = TLS.with(|s| s.borrow_mut().sockets.remove(&sock_id));
1192    super::https::drop_conn(sock_id);
1193    if let Some(rec) = rec {
1194        super::events::instance_call(
1195            &rec.emitter,
1196            "emit",
1197            vec![with_host(|h| h.new_str("close"))],
1198        )?;
1199        with_host(|h| h.decr_handle());
1200        let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1201    }
1202    Ok(())
1203}
1204
1205// ── shared emitter constructor (same shape as net) ───────────────────────────
1206
1207/// Build a native emitter object (`@@native` tag + `@@on`/`@@once` maps + extras),
1208/// sharing the EventEmitter shape with `events`/`net`.
1209pub fn new_emitter_object(tag: &str, mut extra: IndexMap<String, Value>) -> Value {
1210    with_host(|h| {
1211        let on = h.new_object(IndexMap::new());
1212        let once = h.new_object(IndexMap::new());
1213        let mut m = IndexMap::new();
1214        m.insert("@@native".into(), h.new_str(tag));
1215        m.insert("@@on".into(), on);
1216        m.insert("@@once".into(), once);
1217        for (k, v) in extra.drain(..) {
1218            m.insert(k, v);
1219        }
1220        h.new_object(m)
1221    })
1222}