# Changelog

## 2026-02-25 - 25.8.1 - fix(allocator)
switch global allocator from tikv-jemallocator to mimalloc

- Replaced tikv-jemallocator with mimalloc in rust/Cargo.toml workspace dependencies.
- Updated rust/crates/rustproxy/Cargo.toml to use mimalloc as a workspace dependency.
- Updated rust/Cargo.lock: added mimalloc and libmimalloc-sys entries and removed tikv-jemallocator and tikv-jemalloc-sys entries.
- Changed the global allocator in crates/rustproxy/src/main.rs from tikv_jemallocator::Jemalloc to mimalloc::MiMalloc.
- Impact: runtime memory allocator is changed which may affect memory usage and performance; no public API changes but recommend testing memory/performance in deployments.

## 2026-02-24 - 25.8.0 - feat(rustproxy)
use tikv-jemallocator as the global allocator to reduce glibc fragmentation and slow RSS growth; add allocator dependency and enable it in rustproxy, update lockfile, and run tsrust before tests

- Added tikv-jemallocator dependency to rust/Cargo.toml and rust/crates/rustproxy/Cargo.toml
- Enabled tikv_jemallocator as the global allocator in rust/crates/rustproxy/src/main.rs
- Updated rust/Cargo.lock with tikv-jemallocator and tikv-jemalloc-sys entries
- Modified package.json test script to run tsrust before tstest

## 2026-02-24 - 25.7.10 - fix(rustproxy)
Use cooperative cancellation for background tasks, prune stale caches and metric entries, and switch tests to dynamic port allocation to avoid port conflicts

- Introduce tokio_util::sync::CancellationToken to coordinate graceful shutdown of sampling and renewal tasks; await handles on stop and reset the token so the proxy can be restarted.
- Add safety Drop impls (RustProxy, TcpListenerManager) as a last-resort abort path when stop() is not called.
- MetricsCollector: avoid creating per-IP metric entries when the IP has no active connections; prune orphaned per-IP metric maps during sampling; add tests covering late record_bytes races and pruning behavior.
- Passthrough/ConnectionTracker: remove per-connection record/zombie-scanner complexity, add cleanup_stale_timestamps to prune rate-limit timestamp entries, and add an RAII ConnectionTrackerGuard to guarantee connection_closed is invoked.
- HTTP proxy improvements: add prune_stale_routes and reset_round_robin to clear caches (rate limiters, regex cache, round-robin counters) on route updates.
- Tests: add test/helpers/port-allocator.ts and update many tests to use findFreePorts/assertPortsFree (dynamic ports + post-test port assertions) to avoid flakiness and port collisions in CI.

## 2026-02-21 - 25.7.9 - fix(tests)
use high non-privileged ports in tests to avoid conflicts and CI failures

- Updated multiple test files to use high-range, non-privileged ports instead of well-known or conflicting ports.
- Files changed: test/test.acme-http01-challenge.ts, test/test.connection-forwarding.ts, test/test.forwarding-regression.ts, test/test.http-port8080-forwarding.ts, test/test.port-mapping.ts, test/test.smartproxy.ts, test/test.socket-handler.ts.
- Notable port remappings: 8080/8081 -> 47730/47731 (and other proxy ports like 47710), 8443 -> 47711, 7001/7002 -> 47712/47713, 9090 -> 47721, 8181/8182 -> 47732/47733, 9999 -> 47780, TEST_PORT_START/PROXY_PORT_START -> 47750/48750, and TEST_SERVER_PORT/PROXY_PORT -> 47770/47771.

## 2026-02-19 - 25.7.8 - fix(no-changes)
no changes detected; nothing to release

- Current package version: 25.7.7
- Git diff: no changes
- No files modified; no release necessary

## 2026-02-19 - 25.7.7 - fix(proxy)
restrict PROXY protocol parsing to configured trusted proxy IPs and parse PROXY headers before metrics/fast-path so client IPs reflect the real source

- Add proxy_ips: Vec<std::net::IpAddr> to ConnectionConfig with a default empty Vec
- Populate proxy_ips from options.proxy_ips strings in rust/crates/rustproxy/src/lib.rs, parsing each to IpAddr
- Only peek for and parse PROXY v1 headers when the remote IP is contained in proxy_ips (prevents untrusted clients from injecting PROXY headers)
- Move PROXY protocol parsing earlier so metrics and fast-path logic use the effective (real client) IP after PROXY parsing
- If proxy_ips is empty, behavior remains unchanged (no PROXY parsing)

## 2026-02-19 - 25.7.6 - fix(throughput)
add tests for per-IP connection tracking and throughput history; assert per-IP eviction after connection close to prevent memory leak

- Adds runtime assertions for per-IP TCP connection tracking (m.connections.byIP) while a connection is active
- Adds checks for throughput history (m.throughput.history) to ensure history length and timestamps are recorded
- Asserts that per-IP tracking data is evicted after connection close (byIP.size === 0) to verify memory leak fix
- Reorders test checks so per-IP and history metrics are validated during the active connection and totals are validated after close

## 2026-02-19 - 25.7.5 - fix(rustproxy)
prune stale per-route metrics, add per-route rate limiter caching and regex cache, and improve connection tracking cleanup to prevent memory growth

- Prune per-route metrics for routes removed from configuration via MetricsCollector::retain_routes invoked during route table updates
- Introduce per-route shared RateLimiter instances (DashMap) with a request-count-triggered periodic cleanup to avoid stale limiters
- Cache compiled URL-rewrite regexes (regex_cache) to avoid recompiling patterns on every request and insert compiled regex on first use
- Improve upstream connection tracking to remove zero-count entries and guard against underflow, preventing unbounded DashMap growth
- Evict per-IP metrics and timestamps when the last connection for an IP closes so per-IP DashMap entries are fully freed
- Add unit tests validating connection tracking cleanup, per-IP eviction, and route-metrics retention behavior

## 2026-02-19 - 25.7.4 - fix(smart-proxy)
include proxy IPs in smart proxy configuration

- Add proxyIps: this.settings.proxyIPs to proxy options in ts/proxies/smart-proxy/smart-proxy.ts
- Ensures proxy IPs from settings are passed into the proxy implementation (enables proxy IP filtering/whitelisting)

## 2026-02-16 - 25.7.3 - fix(metrics)
centralize connection-closed reporting via ConnectionGuard and remove duplicate explicit metrics.connection_closed calls

- Removed numerous explicit metrics.connection_closed calls from rust/crates/rustproxy-http/src/proxy_service.rs so connection teardown and byte counting are handled by the connection guard / counting body instead of ad-hoc calls.
- Simplified ConnectionGuard in rust/crates/rustproxy-passthrough/src/tcp_listener.rs: removed the disarm flag and disarm() method so Drop always reports connection_closed.
- Stopped disarming the TCP-level guard when handing connections off to HTTP proxy paths (HTTP/WebSocket/streaming flows) to avoid missing or double-reporting metrics.
- Fixes incorrect/duplicate connection-closed metric emission and ensures consistent byte/connection accounting during streaming and WebSocket upgrades.

## 2026-02-16 - 25.7.2 - fix(rustproxy-http)
preserve original Host header when proxying and add X-Forwarded-* headers; add TLS WebSocket echo backend helper and integration test for terminate-and-reencrypt websocket

- Preserve the client's original Host header instead of replacing it with backend host:port when proxying requests.
- Add standard reverse-proxy headers: X-Forwarded-For (appends client IP), X-Forwarded-Host, and X-Forwarded-Proto for upstream requests.
- Ensure raw TCP/HTTP upstream requests copy original headers and skip X-Forwarded-* (which are added explicitly).
- Add start_tls_ws_echo_backend test helper to start a TLS WebSocket echo backend for tests.
- Add integration test test_terminate_and_reencrypt_websocket to verify WS upgrade through terminate-and-reencrypt TLS path.
- Rename unused parameter upstream to _upstream in proxy_service functions to avoid warnings.

## 2026-02-16 - 25.7.1 - fix(proxy)
use TLS to backends for terminate-and-reencrypt routes

- Set upstream.use_tls = true when a route's TLS mode is TerminateAndReencrypt so the proxy re-encrypts to backend servers.
- Add start_tls_http_backend test helper and update integration tests to run TLS-enabled backend servers validating re-encryption behavior.
- Make the selected upstream mutable to allow toggling the use_tls flag during request handling.

## 2026-02-16 - 25.7.0 - feat(routes)
add protocol-based route matching and ensure terminate-and-reencrypt routes HTTP through the full HTTP proxy; update docs and tests

- Introduce a new 'protocol' match field for routes (supports 'http' and 'tcp') and preserve it through cloning/merging.
- Add Rust integration test verifying terminate-and-reencrypt decrypts TLS and routes HTTP traffic via the HTTP proxy (per-request Host/path routing) instead of raw tunneling.
- Add TypeScript unit tests covering protocol field validation, preservation, interaction with terminate-and-reencrypt, cloning, merging, and matching behavior.
- Update README with a Protocol-Specific Routing section and clarify terminate-and-reencrypt behavior (HTTP routed via HTTP proxy; non-HTTP uses raw TLS-to-TLS tunnel).
- Example config: include health check thresholds (unhealthyThreshold and healthyThreshold) in the sample healthCheck settings.

## 2026-02-16 - 25.6.0 - feat(rustproxy)
add protocol-based routing and backend TLS re-encryption support

- Introduce optional route_match.protocol ("http" | "tcp") in Rust and TypeScript route types to allow protocol-restricted routing.
- RouteManager: respect protocol field during matching and treat TLS connections without SNI as not matching domain-restricted routes (except wildcard-only routes).
- HTTP proxy: add BackendStream abstraction to unify plain TCP and tokio-rustls TLS backend streams, and support connecting to upstreams over TLS (upstream.use_tls) with an InsecureBackendVerifier for internal/self-signed backends.
- WebSocket and HTTP forwarding updated to use BackendStream so upstream TLS is handled transparently.
- Passthrough listener: perform post-termination protocol detection for TerminateAndReencrypt; route HTTP flows into HttpProxyService and handle non-HTTP as TLS-to-TLS tunnel.
- Add tests for protocol matching, TLS/no-SNI behavior, and other routing edge cases.
- Add rustls and tokio-rustls dependencies (Cargo.toml/Cargo.lock updates).

## 2026-02-16 - 25.5.0 - feat(tls)
add shared TLS acceptor with SNI resolver and session resumption; prefer shared acceptor and fall back to per-connection when routes specify custom TLS versions

- Add CertResolver that pre-parses PEM certs/keys into CertifiedKey instances for SNI-based lookup and cheap runtime resolution
- Introduce build_shared_tls_acceptor to create a shared ServerConfig with session cache (4096) and Ticketer for session ticket resumption
- Add ArcSwap<Option<TlsAcceptor>> shared_tls_acceptor to tcp_listener for hot-reloadable, pre-built acceptor and update accept loop/handlers to use it
- set_tls_configs now attempts to build and store the shared TLS acceptor, falling back to per-connection acceptors on failure; raw PEM configs are still retained for route-level fallbacks
- Add get_tls_acceptor helper: prefer shared acceptor for performance and session resumption, but build per-connection acceptor when a route requests custom TLS versions

## 2026-02-16 - 25.4.0 - feat(rustproxy)
support dynamically loaded TLS certificates via loadCertificate IPC and include them in listener TLS configs for rebuilds and hot-swap

- Adds loaded_certs: HashMap<String, TlsCertConfig> to RustProxy to store certificates loaded at runtime
- Merge loaded_certs into tls_configs in rebuild and listener hot-swap paths so dynamically loaded certs are served immediately
- Persist loaded certificates on loadCertificate so future rebuilds include them

## 2026-02-15 - 25.3.1 - fix(plugins)
remove unused dependencies and simplify plugin exports

- Removed multiple dependencies from package.json to reduce dependency footprint: @push.rocks/lik, @push.rocks/smartacme, @push.rocks/smartdelay, @push.rocks/smartfile, @push.rocks/smartnetwork, @push.rocks/smartpromise, @push.rocks/smartrequest, @push.rocks/smartrx, @push.rocks/smartstring, @push.rocks/taskbuffer, @types/minimatch, @types/ws, pretty-ms, ws
- ts/plugins.ts: stopped importing/exporting node:https and many push.rocks and third-party modules; plugins now only re-export core node modules (without https), tsclass, smartcrypto, smartlog (+ destination-local), smartrust, and minimatch
- Intended effect: trim surface area and remove unused/optional integrations; patch-level change (no feature/API additions)

## 2026-02-14 - 25.3.0 - feat(smart-proxy)
add background concurrent certificate provisioning with per-domain timeouts and concurrency control

- Add ISmartProxyOptions settings: certProvisionTimeout (ms) and certProvisionConcurrency (default 4)
- Run certProvisionFunction as fire-and-forget background tasks (stores promise on start/route-update and awaited on stop)
- Provision certificates in parallel with a concurrency limit using a new ConcurrencySemaphore utility
- Introduce per-domain timeout handling (default 300000ms) via withTimeout and surface timeout errors as certificate-failed events
- Refactor provisioning into provisionSingleDomain to isolate domain handling, ACME fallback preserved
- Run provisioning outside route update mutex so route updates are not blocked by slow provisioning

## 2026-02-14 - 25.2.2 - fix(smart-proxy)
start metrics polling before certificate provisioning to avoid blocking metrics collection

- Start metrics polling immediately after Rust engine startup so metrics are available without waiting for certificate provisioning.
- Run certProvisionFunction after startup because ACME/DNS-01 provisioning can hang or be slow and must not block observability.
- Code change in ts/proxies/smart-proxy/smart-proxy.ts: metricsAdapter.startPolling() moved to run before provisionCertificatesViaCallback().

## 2026-02-14 - 25.2.1 - fix(smartproxy)
no changes detected in git diff

- The provided diff contains no file changes; no code or documentation updates to release.

## 2026-02-14 - 25.2.0 - feat(metrics)
add per-IP and HTTP-request metrics, propagate source IP through proxy paths, and expose new metrics to the TS adapter

- Add per-IP tracking and IpMetrics in MetricsCollector (active/total connections, bytes, throughput).
- Add HTTP request counters and tracking (total_http_requests, http_requests_per_sec, recent counters and tests).
- Include throughput history (ThroughputSample serialization, retention and snapshotting) and expose history in snapshots.
- Propagate source IP through HTTP and passthrough code paths: CountingBody.record_bytes and MetricsCollector methods now accept source_ip; connection_opened/closed calls include source IP.
- Introduce ForwardMetricsCtx to carry metrics context (collector, route_id, source_ip) into passthrough forwarding routines; update ConnectionGuard to include source_ip.
- TypeScript adapter (rust-metrics-adapter.ts) updated to return per-IP counts, top IPs, per-IP throughput, throughput history mapping, and HTTP request rates/total where available.
- Numerous unit tests added for per-IP tracking, HTTP request tracking, throughput history and ThroughputTracker.history behavior.

## 2026-02-13 - 25.1.0 - feat(metrics)
add real-time throughput sampling and byte-counting metrics

- Add CountingBody wrapper to count HTTP request and response bytes and report them to MetricsCollector.
- Implement lock-free hot-path byte recording and a cold-path sampling API (sample_all) in MetricsCollector with throughput history and configurable retention (default 3600s).
- Spawn a background sampling task in RustProxy (configurable sample_interval_ms) and tear it down on stop so throughput trackers are regularly sampled.
- Instrument passthrough TCP forwarding and socket-relay paths to record per-chunk bytes (lock-free) so long-lived connections contribute to throughput measurements.
- Wrap HTTP request/response bodies with CountingBody in proxy_service to capture bytes_in/bytes_out and report on body completion; connection_closed handling updated accordingly.
- Expose recent throughput metrics to the TypeScript adapter (throughputRecentIn/Out) and pass metrics settings from the TS SmartProxy into Rust.
- Add http-body dependency and update Cargo.toml/Cargo.lock entries for the new body wrapper usage.
- Add unit tests for MetricsCollector throughput tracking and a new end-to-end throughput test (test.throughput.ts).
- Update test certificates (assets/certs cert.pem and key.pem) used by TLS tests.

## 2026-02-13 - 25.0.0 - BREAKING CHANGE(certs)
accept a second eventComms argument in certProvisionFunction, add cert provisioning event types, and emit certificate lifecycle events

- Breaking API change: certProvisionFunction signature changed from (domain: string) => Promise<TSmartProxyCertProvisionObject> to (domain: string, eventComms: ICertProvisionEventComms) => Promise<TSmartProxyCertProvisionObject>. Custom provisioners must accept (or safely ignore) the new second argument.
- New types added and exported: ICertProvisionEventComms, ICertificateIssuedEvent, ICertificateFailedEvent.
- smart-proxy now constructs an eventComms channel that allows provisioners to log/warn/error and set expiry date and source for the issued event.
- Emits 'certificate-issued' (domain, expiryDate, source, isRenewal?) on successful provisioning and 'certificate-failed' (domain, error, source) on failures.
- Updated public exports to include the new types so they are available to consumers.
- Removed readme.byte-counting-audit.md (documentation file deleted).

## 2026-02-13 - 24.0.1 - fix(proxy)
improve proxy robustness: add connect timeouts, graceful shutdown, WebSocket watchdog, and metrics guard

- Add tokio-util CancellationToken to HTTP handlers to support graceful shutdown (stop accepting new requests while letting in-flight requests finish).
- Introduce configurable upstream connect timeout (DEFAULT_CONNECT_TIMEOUT) and return 504 Gateway Timeout on connect timeouts to avoid hanging connections.
- Add WebSocket watchdog with inactivity and max-lifetime checks, activity tracking via AtomicU64, and cancellation-driven tunnel aborts.
- Add ConnectionGuard RAII in passthrough listener to ensure metrics.connection_closed() is called on all exit paths and disarm the guard when handing off to the HTTP proxy.
- Expose HttpProxyService::with_connect_timeout and wire connection timeout from ConnectionConfig into listeners.
- Add tokio-util workspace dependency (CancellationToken) and related code changes across rustproxy-http and rustproxy-passthrough.

## 2026-02-13 - 24.0.0 - BREAKING CHANGE(smart-proxy)
move certificate persistence to an in-memory store and introduce consumer-managed certStore API; add default self-signed fallback cert and change ACME account handling

- Cert persistence removed from Rust side: CertStore is now an in-memory cache (no filesystem reads/writes). Rust no longer persists or loads certs from disk.
- ACME account credentials are no longer persisted by the library; AcmeClient uses ephemeral accounts only and account persistence APIs were removed.
- TypeScript API changes: removed certificateStore option and added ISmartProxyCertStore + certStore option for consumer-provided persistence (loadAll, save, optional remove).
- Default self-signed fallback certificate added (generateDefaultCertificate) and loaded as '*' unless disableDefaultCert is set.
- SmartProxy now pre-loads certificates from consumer certStore on startup and persists certificates by calling certStore.save() after provisioning.
- provisionCertificatesViaCallback signature changed to accept preloaded domains (prevents re-provisioning), and ACME fallback behavior adjusted with clearer logging.
- Rust cert manager methods made infallible for cache-only operations (load_static/store no longer return errors for cache insertions); removed store-backed load_all/remove/base_dir APIs.
- TCP listener tls_configs concurrency improved: switched to ArcSwap<HashMap<...>> so accept loops see hot-reloads immediately.
- Removed dependencies related to filesystem cert persistence from the tls crate (serde_json, tempfile) and corresponding Cargo.lock changes and test updates.

## 2026-02-13 - 23.1.6 - fix(smart-proxy)
disable built-in Rust ACME when a certProvisionFunction is provided and improve certificate provisioning flow

- Pass an optional ACME override into buildRustConfig so Rust ACME can be disabled per-run
- Disable Rust ACME when certProvisionFunction is configured to avoid provisioning race conditions
- Normalize routing glob patterns into concrete domain identifiers for certificate provisioning (expand leading-star globs and warn on unsupported patterns)
- Deduplicate domains during provisioning to avoid repeated attempts
- When the callback returns 'http01', explicitly trigger Rust ACME for the route via bridge.provisionCertificate and log success/failure

## 2026-02-13 - 23.1.5 - fix(smart-proxy)
provision certificates for wildcard domains instead of skipping them

- Removed early continue that skipped domains containing '*' in the domain loop
- Now calls provisionFn for wildcard domains so certificate provisioning can proceed for wildcard hosts
- Fixes cases where wildcard domains never had certificates requested

## 2026-02-12 - 23.1.4 - fix(tests)
make tests more robust and bump small dependencies

- Bump dependencies: @push.rocks/smartrust ^1.2.1 and minimatch ^10.2.0
- Replace hardcoded ports with named constants (ECHO_PORT, PROXY_PORT, PROXY_PORT_1/2) to avoid collisions between tests
- Add server 'error' handlers and reject listen promises on server errors to prevent silent hangs
- Reduce test timeouts and intervals (shorter test durations, more frequent pings) to speed up test runs
- Ensure proxy is stopped between tests and remove forced process.exit; export tap.start() consistently
- Adjust assertions to match the new shorter ping/response counts

## 2026-02-12 - 23.1.3 - fix(rustproxy)
install default rustls crypto provider early; detect and skip raw fast-path for HTTP connections and return proper HTTP 502 when no route matches

- Install ring-based rustls crypto provider at startup to prevent panics from instant-acme/hyper-rustls calling ClientConfig::builder() before TLS listeners are initialized
- Add a non-blocking 10ms peek to detect HTTP traffic in the TCP passthrough fast-path to avoid misrouting HTTP and ensure HTTP proxy handles CORS, errors, and request-level routing
- Skip the fast-path and fall back to the HTTP proxy when HTTP is detected (with a debug log)
- When no route matches for detected HTTP connections, send an HTTP 502 Bad Gateway response and close the connection instead of silently dropping it

## 2026-02-11 - 23.1.2 - fix(core)
use node: scoped builtin imports and add route unit tests

- Replaced bare Node built-in imports (events, fs, http, https, net, path, tls, url, http2, buffer, crypto) with 'node:' specifiers for ESM/bundler compatibility (files updated include ts/plugins.ts, ts/core/models/socket-types.ts, ts/core/utils/enhanced-connection-pool.ts, ts/core/utils/socket-tracker.ts, ts/protocols/common/fragment-handler.ts, ts/protocols/tls/sni/client-hello-parser.ts, ts/protocols/tls/sni/sni-extraction.ts, ts/protocols/websocket/utils.ts, ts/tls/sni/sni-handler.ts).
- Added new unit tests (test/test.bun.ts and test/test.deno.ts) covering route helpers, validators, matching, merging and cloning to improve test coverage.

## 2026-02-11 - 23.1.1 - fix(rust-proxy)
increase rust proxy bridge maxPayloadSize to 100 MB and bump dependencies

- Set maxPayloadSize to 100 * 1024 * 1024 (100 MB) in ts/proxies/smart-proxy/rust-proxy-bridge.ts to support large route configs
- Bump devDependency @types/node from ^25.2.2 to ^25.2.3
- Bump dependency @push.rocks/smartrust from ^1.1.1 to ^1.2.0

## 2026-02-10 - 23.1.0 - feat(rust-bridge)
integrate tsrust to build and locate cross-compiled Rust binaries; refactor rust-proxy bridge to use typed IPC and streamline process handling; add @push.rocks/smartrust and update build/dev dependencies

- Add tsrust to the build script and include dist_rust candidates when locating the Rust binary (enables cross-compiled artifacts produced by tsrust).
- Remove the old rust-binary-locator and refactor rust-proxy-bridge to use explicit, typed IPC command definitions and improved process spawn/cleanup logic.
- Introduce @push.rocks/smartrust for type-safe JSON IPC and export it via plugins; update README with expanded metrics documentation and change initialDataTimeout default from 60s to 120s.
- Add rust/.cargo/config.toml with aarch64 linker configuration to support cross-compilation for arm64.
- Bump several devDependencies and runtime dependencies (e.g. @git.zone/tsbuild, @git.zone/tstest, @push.rocks/smartserve, @push.rocks/taskbuffer, ws, minimatch, etc.).
- Update runtime message guiding local builds to use 'pnpm build' (tsrust) instead of direct cargo invocation.

## 2026-02-09 - 23.0.0 - BREAKING CHANGE(proxies/nftables-proxy)
remove nftables-proxy implementation, models, and utilities from the repository

- Deleted nftables-proxy module files under ts/proxies/nftables-proxy (index, models, utils, command executor, validators, etc.)
- Removed nftables-proxy exports from ts/index.ts and ts/proxies/index.ts
- Updated smart-proxy types to drop dependency on nftables proxy models
- Breaking change: any consumers importing nftables-proxy will no longer find those exports; update imports or install/use the extracted/alternative package if applicable

## 2026-02-09 - 22.6.0 - feat(smart-proxy)
add socket-handler relay, fast-path port-only forwarding, metrics and bridge improvements, and various TS/Rust integration fixes

- Add Unix-domain socket relay for socket-handler routes so Rust can hand off matched connections to TypeScript handlers (metadata JSON + initial bytes, relay implementation in Rust and SocketHandlerServer in TS).
- Implement fast-path port-only forwarding in the TCP accept/handler path to forward simple non-TLS, port-only routes immediately without peeking at client data (improves server-speaks-first protocol handling).
- Use ArcSwap for route manager hot-reload visibility in accept loops and share socket_handler_relay via Arc<RwLock> so listeners see relay path updates immediately.
- Enhance SNI/HTTP parsing: add extract_http_path and extract_http_host to aid domain/path matching from initial data.
- Improve RustProxy shutdown/kill handling: remove listeners, reject pending requests, destroy stdio pipes and unref process to avoid leaking handles.
- Enhance Rust <-> TS metrics bridge and adapter: add immediate poll(), map Rust JSON fields to IMetrics (per-route active/throughput/totals), and use safer polling/unref timers.
- SocketHandlerServer enhancements: track active sockets, destroy on stop, pause/resume to prevent data loss, support async socketHandler callbacks and dynamic function-based target forwarding (resolve host/port functions and forward).
- TypeScript smart-proxy lifecycle tweaks: only set bridge relay after Rust starts, guard unexpected-exit emission when intentionally stopping, stop polling and remove listeners on stop, add stopping flag.
- Misc: README and API ergonomics updates (nft proxy option renames and config comments), various test updates to use stable http.request helper, adjust timeouts/metrics sampling and assertions, and multiple small bugfixes in listeners, timeouts and TLS typings. 

## 2026-02-09 - 22.5.0 - feat(rustproxy)
introduce a Rust-powered proxy engine and workspace with core crates for proxy functionality, ACME/TLS support, passthrough and HTTP proxies, metrics, nftables integration, routing/security, management IPC, tests, and README updates

- Add Rust workspace and multiple crates: rustproxy, rustproxy-config, rustproxy-routing, rustproxy-tls, rustproxy-passthrough, rustproxy-http, rustproxy-nftables, rustproxy-metrics, rustproxy-security
- Implement ACME integration (instant-acme) and an HTTP-01 challenge server with certificate lifecycle management
- Add TLS management: cert store, cert manager, SNI resolver, TLS acceptor/connector and certificate hot-swap support
- Implement TCP/TLS passthrough engine with ClientHello SNI parsing, PROXY v1 support, connection tracking and bidirectional forwarder
- Add Hyper-based HTTP proxy components: request/response filtering, CORS, auth, header templating and upstream selection with load balancing
- Introduce metrics (throughput tracker, metrics collector) and log deduplication utilities
- Implement nftables manager and rule builder (safe no-op behavior when not running as root)
- Add route types, validation, helpers, route manager and matchers (domain/path/header/ip)
- Provide management IPC (JSON over stdin/stdout) for TypeScript wrapper control (start/stop/add/remove ports, load certificates, etc.)
- Include extensive unit and integration tests, test helpers, and an example Rust config.json
- Update README to document the Rust-powered engine, new features and rustBinaryPath lookup

## 2026-01-31 - 22.4.2 - fix(tests)
shorten long-lived connection test timeouts and update certificate metadata timestamps

- Reduced test timeouts from 65–70s to 60s and shortened internal waits from ~61–65s to 55s to ensure tests complete within CI runner limits (files changed: test/test.long-lived-connections.ts, test/test.websocket-keepalive.node.ts).
- Updated log message to reflect the new 55s wait.
- Bumped certificate metadata timestamps in certs/static-route/meta.json (issueDate, savedAt, expiryDate).

## 2026-01-30 - 22.4.1 - fix(smartproxy)
improve certificate manager mocking in tests, enhance IPv6 validation, and record initial bytes for connection metrics

- Add createMockCertManager and update tests to fully mock createCertificateManager to avoid real ACME calls and make provisioning deterministic
- Record initial data chunk bytes in route-connection-handler and report them to metricsCollector.recordBytes to improve metrics accuracy
- Improve IPv6 validation regex to accept IPv6-mapped IPv4 addresses (::ffff:x.x.x.x)
- Add/set missing mock methods used in tests (setRoutes, generateConnectionId, trackConnectionByRoute, validateAndTrackIP) and small test adjustments (route names, port changes)
- Make test robustness improvements: wait loops for connection cleanup, increase websocket keepalive timeout, and other minor test fixes/whitespace cleanups
- Update certificate meta timestamps (test fixtures)

## 2026-01-30 - 22.4.0 - feat(smart-proxy)
calculate when SNI is required for TLS routing and allow session tickets for single-target passthrough routes; add tests, docs, and npm metadata updates

- Add calculateSniRequirement() and isWildcardOnly() to determine when SNI is required for routing decisions
- Use the new calculation to allow TLS session tickets for single-route passthrough or wildcard-only domains and block them when SNI is required
- Replace previous heuristic in route-connection-handler with the new SNI-based logic
- Add comprehensive unit tests (test/test.sni-requirement.node.ts) covering multiple SNI scenarios
- Update readme.hints.md with Smart SNI Requirement documentation and adjust troubleshooting guidance
- Update npmextra.json keys, add release registries and adjust tsdoc/CI metadata

## 2026-01-30 - 22.3.0 - feat(docs)
update README with installation, improved feature table, expanded quick-start, ACME/email example, API options interface, and clarified licensing/trademark text

- Added Installation section with npm/pnpm commands
- Reformatted features into a markdown table for clarity
- Expanded Quick Start example and updated ACME email placeholder
- Added an ISmartProxyOptions interface example showing acme/defaults/behavior options
- Clarified license file path and expanded trademark/legal wording
- Minor editorial and formatting improvements throughout the README

## 2026-01-30 - 22.2.0 - feat(proxies)
introduce nftables command executor and utilities, default certificate provider, expanded route/socket helper modules, and security improvements

- Added NftCommandExecutor with retry, temp-file support, sync execution, availability and conntrack checks.
- Refactored NfTablesProxy to use executor/utils (normalizePortSpec, validators, port normalizer, IP family filtering) and removed inline command/validation code.
- Introduced DefaultCertificateProvider to replace the deprecated CertificateManager; HttpProxy now uses DefaultCertificateProvider (CertificateManager exported as deprecated alias for compatibility).
- Added extensive route helper modules (http, https, api, load-balancer, nftables, dynamic, websocket, security, socket handlers) to simplify route creation and provide reusable patterns.
- Enhanced SecurityManagers: centralized security utilities (normalizeIP, isIPAuthorized, parseBasicAuthHeader, cleanup helpers), added validateAndTrackIP and JWT token verification, better IP normalization and rate tracking.
- Added many utility modules under ts/proxies/nftables-proxy/utils (command executor, port spec normalizer, rule validator) and exposed them via barrel export.

## 2025-12-09 - 22.1.1 - fix(tests)
Normalize route configurations in tests to use name (remove id) and standardize route names

- Removed deprecated id properties from route configurations in multiple tests and rely on the name property instead
- Standardized route.name values to kebab-case / lowercase (examples: 'tcp-forward', 'tls-passthrough', 'domain-a', 'domain-b', 'test-forward', 'nftables-test', 'regular-test', 'forward-test', 'test-forward', 'tls-test')
- Added explicit names for inner and outer proxies in proxy-chain-cleanup test ('inner-backend', 'outer-frontend')
- Updated certificate metadata timestamps in certs/static-route/meta.json

## 2025-12-09 - 22.1.0 - feat(smart-proxy)
Improve connection/rate-limit atomicity, SNI parsing, HttpProxy & ACME orchestration, and routing utilities

- Fix race conditions for per-IP connection limits by introducing atomic validate-and-track flow (SecurityManager.validateAndTrackIP) and propagating connectionId for atomic tracking.
- Add connection-manager createConnection options (connectionId, skipIpTracking) and avoid double-tracking IPs when validated atomically.
- RouteConnectionHandler now generates connection IDs earlier and uses atomic IP validation to prevent concurrent connection bypasses; cleans up IP tracking on global-limit rejects.
- Enhanced TLS SNI extraction and ClientHello parsing: robust fragmented ClientHello handling, PSK-based SNI extraction for TLS 1.3 resumption, tab-reactivation heuristics and improved logging (new client-hello-parser and sni-extraction modules).
- HttpProxy integration improvements: HttpProxyBridge initialized/synced from SmartProxy, forwardToHttpProxy forwards initial data and preserves client IP via CLIENT_IP header, robust handling of client disconnects during setup.
- Certificate manager (SmartCertManager) improvements: better ACME initialization sequence (deferred provisioning until ports are bound), improved challenge route add/remove handling, custom certificate provisioning hook, expiry handling fallback behavior and safer error messages for port conflicts.
- Route/port orchestration refactor (RouteOrchestrator): port usage mapping, safer add/remove port sequences, NFTables route lifecycle updates and certificate manager recreation on route changes.
- PortManager now refcounts ports and reuses existing listeners instead of rebinding; provides helpers to add/remove/update multiple ports and improved error handling for EADDRINUSE.
- Connection cleanup, inactivity and zombie detection hardened: batched cleanup queue, optimized inactivity checks, half-zombie detection and safer shutdown workflows.
- Metrics, routing helpers and validators: SharedRouteManager exposes expandPortRange/getListeningPorts, route helpers add convenience HTTPS/redirect/loadbalancer builders, route-validator domain rules relaxed to allow 'localhost', '*' and IPs, and tests updated accordingly.
- Tests updated to reflect behavioral changes (connection limit checks adapted to detect closed/ reset connections, HttpProxy integration test skipped in unit suite to avoid complex TLS setup).

## 2025-12-09 - 22.0.0 - BREAKING CHANGE(smart-proxy/utils/route-validator)
Consolidate and refactor route validators; move to class-based API and update usages

Replaced legacy route-validators.ts with a unified route-validator.ts that provides a class-based RouteValidator plus the previous functional API (isValidPort, isValidDomain, validateRouteMatch, validateRouteAction, validateRouteConfig, validateRoutes, hasRequiredPropertiesForAction, assertValidRoute) for backwards compatibility. Updated utils exports and all imports/tests to reference the new module. Also switched static file loading in certificate manager to use SmartFileFactory.nodeFs(), and added @push.rocks/smartserve to devDependencies.

- Rename and consolidate validator module: route-validators.ts removed; route-validator.ts added with RouteValidator class and duplicated functional API for compatibility.
- Updated exports in ts/proxies/smart-proxy/utils/index.ts and all internal imports/tests to reference './route-validator.js' instead of './route-validators.js'.
- Certificate manager now uses plugins.smartfile.SmartFileFactory.nodeFs() to load key/cert files (safer factory usage instead of direct static calls).
- Added @push.rocks/smartserve to devDependencies in package.json.
- Because the validator filename and some import paths changed, this is a breaking change for consumers importing the old module path.

## 2025-08-19 - 21.1.7 - fix(route-validator)
Relax domain validation to accept 'localhost', prefix wildcards (e.g. *example.com) and IP literals; add comprehensive domain validation tests

- Allow 'localhost' as a valid domain pattern in route validation
- Support prefix wildcard patterns like '*example.com' in addition to '*.example.com'
- Accept IPv4 and IPv6 literal addresses in domain validation
- Add test coverage: new test/test.domain-validation.ts with many real-world and edge-case patterns

## 2025-08-19 - 21.1.6 - fix(ip-utils)
Fix IP wildcard/shorthand handling and add validation test

- Support shorthand IPv4 wildcard patterns (e.g. '10.*', '192.168.*') by expanding them to full 4-octet patterns before matching
- Normalize and expand patterns in IpUtils.isGlobIPMatch and SharedSecurityManager IP checks to ensure consistent minimatch comparisons
- Relax route validator wildcard checks to accept 1-4 octet wildcard specifications for IPv4 patterns
- Add test harness test-ip-validation.ts to exercise common wildcard/shorthand IP patterns

## 2025-08-19 - 21.1.5 - fix(core)
Prepare patch release: documentation, tests and stability fixes (metrics, ACME, connection cleanup)

- Byte counting and throughput: per-route and per-IP throughput trackers with per-second sampling; removed double-counting and improved sampling buffers for accurate rates
- HttpProxy and forwarding: Ensure metricsCollector.recordBytes() is called in forwarding paths so throughput is recorded reliably
- ACME / Certificate Manager: support for custom certProvisionFunction with configurable fallback to ACME (http01) and improved challenge route lifecycle
- Connection lifecycle and cleanup: improved lifecycle component timer/listener cleanup, better cleanup queue batching and zombie/half-zombie detection
- Various utilities and stability improvements: enhanced IP utils, path/domain matching improvements, safer socket handling and more robust fragment/ClientHello handling
- Tests and docs: many test files and readme.hints.md updated with byte-counting audit, connection cleanup and ACME guidance

## 2025-08-14 - 21.1.4 - fix(security)
Critical security and stability fixes

- Fixed critical socket.emit override vulnerability that was breaking TLS connections
- Implemented comprehensive socket cleanup with new socket tracker utility
- Improved code organization by extracting RouteOrchestrator from SmartProxy
- Fixed IPv6 loopback detection for proper IPv6 support
- Added memory bounds to prevent unbounded collection growth
- Fixed certificate manager race conditions with proper synchronization
- Unreferenced long-lived timers to prevent process hanging
- Enhanced route validation for socket-handler actions
- Fixed header parsing when extractFullHeaders option is enabled

## 2025-07-22 - 21.1.1 - fix(detection)
Fix SNI detection in TLS detector

- Restored proper TLS detector implementation with ClientHello parsing
- Fixed imports to use new protocols module locations
- Added missing detectWithContext method for fragmented detection
- Fixed method names to match BufferAccumulator interface
- Removed unused import readUInt24BE

## 2025-07-21 - 21.1.0 - feat(protocols)
Refactor protocol utilities into centralized protocols module

- Moved TLS utilities from `ts/tls/` to `ts/protocols/tls/`
- Created centralized protocol modules for HTTP, WebSocket, Proxy, and TLS
- Core utilities now delegate to protocol modules for parsing and utilities
- Maintains backward compatibility through re-exports in original locations
- Improves code organization and separation of concerns

## 2025-07-22 - 21.0.0 - BREAKING_CHANGE(forwarding)
Remove legacy forwarding module

- Removed the `forwarding` namespace export from main index
- Removed TForwardingType and all forwarding handlers
- Consolidated route helper functions into route-helpers.ts
- All functionality is now available through the route-based system
- MIGRATION: Replace `import { forwarding } from '@push.rocks/smartproxy'` with direct imports of route helpers

## 2025-07-21 - 20.0.2 - fix(docs)
Update documentation to improve clarity

- Enhanced readme with clearer breaking change warning for v20.0.0
- Fixed example email address from ssl@bleu.de to ssl@example.com
- Added load balancing and failover features to feature list
- Improved documentation structure and examples

## 2025-07-20 - 20.0.1 - BREAKING_CHANGE(routing)
Refactor route configuration to support multiple targets

- Changed route action configuration from single `target` to `targets` array
- Enables load balancing and failover capabilities with multiple upstream targets
- Updated all test files to use new `targets` array syntax
- Automatic certificate metadata refresh

## 2025-06-01 - 19.5.19 - fix(smartproxy)
Fix connection handling and improve route matching edge cases

- Enhanced cleanup logic to prevent connection accumulation under rapid retry scenarios
- Improved matching for wildcard domains and path parameters in the route configuration
- Minor refactoring in async utilities and internal socket handling for better performance
- Updated test suites and documentation for clearer configuration examples

## 2025-05-29 - 19.5.3 - fix(smartproxy)
Fix route security configuration location and improve ACME timing tests and socket mock implementations

- Move route security from action.security to the top-level route.security to correctly enforce IP allow/block lists (addresses failing in test.route-security.ts)
- Update readme.problems.md to document the routing security configuration issue with proper instructions
- Adjust certificate metadata in certs/static-route/meta.json with updated timestamps
- Update test.acme-timing.ts to export default tap.start() instead of tap.start() to ensure proper parsing
- Improve socket simulation and event handling mocks in test.http-fix-verification.ts and test.http-forwarding-fix.ts to more reliably mimic net.Socket behavior
- Minor adjustments in multiple test files to ensure proper port binding, race condition handling and route lookups (e.g. getRoutesForPort implementation)

## 2025-05-29 - 19.5.2 - fix(test)
Fix ACME challenge route creation and HTTP request parsing in tests

- Replaced the legacy ACME email 'test@example.com' with 'test@acmetest.local' to avoid forbidden domain issues.
- Mocked the CertificateManager in test/test.acme-route-creation to simulate immediate ACME challenge route addition.
- Adjusted updateRoutes callback to capture and verify challenge route creation.
- Enhanced the HTTP request parsing in socket handler by capturing and asserting parsed request details (method, path, headers).

## 2025-05-29 - 19.5.1 - fix(socket-handler)
Fix socket handler race condition by differentiating between async and sync handlers. Now, async socket handlers complete their setup before initial data is emitted, ensuring that no data is lost. Documentation and tests have been updated to reflect this change.

- Added detailed explanation in readme.hints.md about the race condition issue, root cause, and solution implementation.
- Provided a code snippet that checks if the socket handler returns a Promise and waits for its resolution before emitting initial data.
- Updated tests (test.socket-handler-race.ts, test.socket-handler.simple.ts, test.socket-handler.ts) to verify correct behavior of async handlers.

## 2025-05-28 - 19.5.0 - feat(socket-handler)
Add socket-handler support for custom socket handling in SmartProxy

- Introduce new action type 'socket-handler' in IRouteAction to allow users to provide a custom socket handler function.
- Update the RouteConnectionHandler to detect 'socket-handler' actions and invoke the handler with the raw socket, giving full control to the user.
- Provide optional context (such as route configuration, client IP, and port) to the socket handler if needed.
- Add helper functions in route-helpers for creating socket handler routes and common patterns like echo, proxy, and line-based protocols.
- Include a detailed implementation plan and usage examples in readme.plan.md.

## 2025-05-28 - 19.4.3 - fix(smartproxy)
Improve port binding intelligence and ACME challenge route management; update route configuration tests and dependency versions.

- Bumped dev dependency versions in package.json (tsbuild from ^2.5.1 to ^2.6.4, tstest from ^1.9.0 to ^2.3.1, @types/node updated, smartfile from ^11.2.0 to ^11.2.5, smartlog from ^3.1.7 to ^3.1.8)
- Removed readme.plan.md containing legacy development plan information
- Normalized route configuration properties across tests (using 'ports' and 'domains' instead of legacy 'port' or 'domain')
- Enhanced PortManager with reference counting and smarter port conflict detection to avoid redundant bindings
- Refined ACME challenge route integration to merge with existing port bindings and improve error handling
- Adjusted test expectations (e.g. using toEqual instead of toBe, and improved timeout handling) to align with current API changes

## 2025-05-20 - 19.4.2 - fix(dependencies)
Update dependency versions: upgrade @types/node to ^22.15.20 and @push.rocks/smartlog to ^3.1.7 in package.json

- Bump @types/node from ^22.15.19 to ^22.15.20
- Bump @push.rocks/smartlog from ^3.1.3 to ^3.1.7

## 2025-05-20 - 19.4.1 - fix(smartproxy)
Bump @push.rocks/smartlog to ^3.1.3 and improve ACME port binding behavior in SmartProxy

- Updated package.json to use @push.rocks/smartlog version ^3.1.3
- Enhanced tests (test.http-port8080-simple.ts) to verify improved port binding intelligence for ACME challenge routes
- Ensured that existing port listeners are reused and not re-bound when updating routes

## 2025-05-20 - 19.4.0 - feat(certificate-manager, smart-proxy)
Improve port binding intelligence for ACME challenges

- Reordered SmartProxy initialization flow to bind ports before initializing the certificate manager
- Enhanced port binding logic to better handle ACME challenge routes
- Improved error detection and reporting for port binding conflicts
- Added better diagnostics for ACME challenge port issues
- Made route updates more intelligent with detailed port tracking
- Fixed race condition where ACME routes were added before port 80 was bound
- Added special handling for ACME port conflicts with improved error messages

## 2025-05-20 - 19.3.14 - fix(certificate-manager, smart-proxy)
Add error handling around logger calls in route update callback

- Added try/catch blocks around logger calls in certificate-manager.ts
- Added try/catch blocks around logger calls in smart-proxy.ts related to route updates
- Provided fallback to console.log when logger fails
- Ensured core route update functionality continues to work even if logging fails

## 2025-05-20 - 19.3.13 - fix(port-manager, certificate-manager)
Improve port binding and ACME challenge route integration in SmartProxy

- Added reference counting in PortManager so that routes sharing the same port reuse the existing binding.
- Enhanced error handling to distinguish internal port conflicts from external ones, with more descriptive messages.
- Adjusted ACME challenge route addition to merge with existing port bindings when port is already in use.
- Refactored updateRoutes to release orphaned ports and bind only new required ports, minimizing rebinding operations.
- Improved certificate-manager logic to provide clearer error notifications when ACME port conflicts occur.

## 2025-05-19 - 19.3.12 - fix(tests)
Update test mocks to include provisionAllCertificates methods in certificate manager stubs and related objects.

- Added async provisionAllCertificates functions to several test mocks (e.g. in test.port80-management.node.ts, test.route-callback-simple.ts, test.route-update-callback.node.ts, and test.simple-acme-mock.ts) to simulate ACME certificate provisioning.
- Enhanced logging and port-add history debugging for ACME challenge port addition.

## 2025-05-19 - 19.3.11 - fix(logger)
Replace raw console logging calls with structured logger usage across certificate management, connection handling, and route processing for improved observability.

- Replaced console.log, console.warn, and console.error in SmartCertManager with logger.log for more consistent logging.
- Updated ConnectionManager and RouteConnectionHandler to log detailed connection events using a structured logger.
- Enhanced logging statements with contextual metadata such as connection IDs, remote IPs, target information, and component identifiers.
- Standardized log output across proxy modules to aid in debugging and monitoring.

## 2025-05-19 - 19.3.10 - fix(certificate-manager, smart-proxy)
Fix race condition in ACME certificate provisioning and refactor certificate manager initialization to defer provisioning until after port listeners are active

- Removed superfluous provisionCertificatesAfterPortsReady method
- Made provisionAllCertificates public so that SmartProxy.start() calls it after ports are listening
- Updated SmartProxy.start() to wait for port setup (via PortManager) before triggering certificate provisioning
- Improved ACME HTTP-01 challenge timing so that port 80 (or configured ACME port) is guaranteed to be ready
- Updated documentation (changelog and Acme timing docs) and tests to reflect the change

## 2025-05-19 - 19.3.10 - refactor(certificate-manager, smart-proxy)
Simplify certificate provisioning code by removing unnecessary wrapper method

- Removed superfluous SmartCertManager.provisionCertificatesAfterPortsReady() method
- Made SmartCertManager.provisionAllCertificates() public instead
- Updated SmartProxy.start() to call provisionAllCertificates() directly
- Updated documentation and tests to reflect the change
- No functional changes, just code simplification

## 2025-05-19 - 19.3.9 - fix(certificate-manager, smart-proxy)
Fix ACME certificate provisioning timing to ensure ports are listening first

- Fixed race condition where certificate provisioning would start before ports were listening
- Modified SmartCertManager.initialize() to defer certificate provisioning
- Added SmartCertManager.provisionCertificatesAfterPortsReady() for delayed provisioning
- Updated SmartProxy.start() to call certificate provisioning after ports are ready