Skip to content

Node package

David Reed edited this page Nov 20, 2026 · 2 revisions

The holywisp npm package runs the holyWisp server inside a Node.js application. It carries a prebuilt binary, starts it as a child process, and hands it the WebSocket upgrades your own HTTP server receives. The class and option names follow wispurr's wrapper, so code written for that one mostly changes its import. Source: node/, with node/README.md as the package's own reference.

Install

npm install holywisp            # the newest release
npm install holywisp@nightly    # the newest commit of master that passed its tests

Node 20 or newer. The package has no runtime dependencies, no install script, and compiles nothing on your machine. A nightly has a version like 0.5.4-nightly.202611110643.g1a2b3c4 (the version in package.json, the UTC time, the commit), and the binary inside reports the same with --version. Pin the exact nightly you tested with.

A minimal server

import { createServer } from "node:http";
import { holyWisp } from "holywisp";

const wisp = new holyWisp({ logLevel: "info" });
await wisp.start(4); // four worker threads; 0 = one per CPU

const server = createServer((req, res) => {
	res.end("my app\n");
});
server.on("upgrade", (req, socket, head) => {
	if (req.url?.startsWith("/wisp/")) wisp.route(req, socket, head);
	else socket.destroy();
});
server.listen(8080);

A Wisp client then connects to ws://<your host>:8080/wisp/. The server itself listens on 127.0.0.1:6001 (or the next free port), reachable only through route().

With Express, the upgrade handler goes on the server that app.listen() returns:

const server = app.listen(8080);
server.on("upgrade", (req, socket, head) => wisp.route(req, socket, head));

The holyWisp class

Member What it does
new holyWisp(options?) Checks the options and throws a TypeError on a bad one. Starts nothing.
start(workers = 1) Starts the server with that many worker threads (0 to 1024; 0 is one per CPU) and resolves once /health answers. Rejects with the server's own message if it refuses the config, with secrets replaced by [redacted]. Gives up after 10 s.
route(req, socket, head) Handler for the HTTP server's upgrade event. See Who the client is.
routeRequest(req, res) Answers GET /webtransport.json and returns true; returns false for anything else, or when webTransport is not set.
stats() Fetches GET /stats and returns it parsed, as a holyWispStats. That type declares every field the server writes: connections by transport and per worker, streams and why they ended, bytes, refusals by cause, the queue budget, WARP and the upstream route, WebTransport and QUIC, the timing histograms and the version. The server only adds fields to it. The fields are on Stats and monitoring.
stop(timeoutMs = 10000) Asks the server to shut down (SIGTERM; on Windows, by closing its stdin) and sends SIGKILL if it has not exited in time. Cancels a pending restart.
kill() SIGKILL now. Cancels a pending restart.
isRunning, port, ports, pid State of the current server process. ports has one entry while running, none when stopped.
restarts How many times autoRestart has brought the server back since start().
config The options as given, with host filled in.

The module also exports holyWisp as its default export, the option types (holyWispOptions, FloodProtectionConfig, ReputationConfig and others) and the stats types (holyWispStats, with holyWispStatsReasons for the close-reason counts and holyWispStatsHistogram for a timing histogram).

Who the client is

The server enforces its limits and reputation per client address, and behind route() every connection comes from this process on loopback. So route() tells the server who the client is:

  • It writes the socket's peer address into the first of trustedHeaders (X-Forwarded-For by default), directly after the request line, before any header the client sent.
  • It drops every copy of those headers that arrived with the request, in any case and however often sent, unless the peer is in trustedProxies.
  • It sends X-HolyWisp-Proxy-Secret with a random secret made for each server process, and drops a client's own header of that name. The server believes forwarding headers from 127.0.0.1 and ::1 only with that secret, so another local process that connects to the server's port is treated as itself.

If your Node server is behind nginx or a CDN, list it:

new holyWisp({ trustedProxies: ["127.0.0.1", "10.0.0.0/8"] });

Requests from those peers keep their X-Forwarded-For, with the peer appended, and the server walks the list from the right to the first address that is not a trusted hop. The wrapper keeps the right-hand end of a list that would pass 400 bytes, since the server cuts long values and the right end is the part the proxies wrote. List a header other than X-Forwarded-For in trustedHeaders only if the proxy in front overwrites it on every request. parseRealIP: false makes the socket's peer the client always.

Cases route() handles itself:

Situation Answer
The server is not running (not started, or between a crash and its restart) 503 Service Unavailable
The server does not answer the connection 502 Bad Gateway
The socket's peer address is there but does not parse 403 Forbidden
The socket has no peer address at all (your HTTP server listens on a Unix socket) The client counts as 127.0.0.1, and the log says so once. List 127.0.0.1 in trustedProxies if a proxy on that socket sends X-Forwarded-For.

A proxy that connects to the server's own port (with host: "0.0.0.0") does not have the secret, so its headers are not believed even if it is in trustedProxies. Send its traffic through route().

Options

All options are optional. An option left out is not passed, and the server's own default applies (holywisp --help, or Configuration). The wrapper sets its own value for a few:

Option Wrapper default Server flag
port 6001, or the next free port above it; 0 asks the OS for any port
host 127.0.0.1, also for undefined and "" host
binary the bundled binary, or $HOLYWISP_BIN (path of the server to run)
autoRestart true (wrapper only)
logLevel "warn"; "none" runs the server at error and shows nothing log-level
trustedHeaders ["X-Forwarded-For"] trusted-headers-reset, then trusted-header
trustedProxies [], plus 127.0.0.1 and ::1 always trusted-proxy

Everything else maps one to one:

Option Server flag
allowTCP, allowUDP, allowDirectIP allow-tcp, allow-udp, allow-direct-ip
allowPrivateIPs, allowLoopbackIPs, allowLinkLocalIPs allow-private, allow-loopback, allow-link-local
blacklist.hostnames, blacklist.ports block-host, block-port
whitelist.hostnames, whitelist.ports allow-host, allow-port
enableV2, enableTwisp, motd enable-v2, enable-twisp, motd
streamCredit, uploadCredit stream-credit, upload-credit
passwordUsers, passwordAuth, passwordAuthRequired password-user, password-required
parseRealIP (see above)
allowedOrigins, policyFile allow-origin, policy-file
connectionsLimitPerIP, connectionWindowSeconds, bandwidthLimitKbps connections-limit-per-ip, connection-window-s, bandwidth-limit-kbps
floodProtection.enabled flood-protection
floodProtection.maxConnectsPerSourceIPPerSecond max-connects-per-source-per-second
floodProtection.maxConnectsPerDestPerSecond, .maxConnectsPerDestPerMinute max-connects-per-dest-per-second, max-connects-per-dest-per-minute
floodProtection.maxInFlightSyns, .maxInFlightSynsPerIP max-in-flight-syns, max-in-flight-syns-per-ip
floodProtection.maxConcurrentStreamsPerConnection max-streams-per-conn
floodProtection.maxConcurrentConnections, .maxConcurrentConnectionsPerIP max-concurrent-connections, max-concurrent-connections-per-ip
floodProtection.maxHandshakesPerIP max-handshakes-per-ip
floodProtection.synFloodSignature.{enabled, windowMs, minSamples, failedHandshakeRatio} syn-signature, syn-signature-window-ms, syn-signature-min-samples, syn-signature-failed-ratio
floodProtection.wsCloseAfterViolations, .logBlockedDials ws-close-after-violations, log-blocked-dials
reputation.enabled, .storePath, .saveIntervalSeconds reputation, reputation-store, reputation-save-interval-s
reputation.scoreDecayPerHour, .evictAfterDays reputation-decay-per-hour, reputation-evict-after-days
reputation.thresholds.{warn, throttle, strict} reputation-warn, reputation-throttle, reputation-strict
reputation.weights, reputation.destinationWeights reputation-weight EVENT:N, reputation-dest-weight EVENT:N
proxy, proxyUDP ("direct" or "refuse") proxy, proxy-udp
dnsServers, dnsResultOrder ("ipv4first", "ipv6first", "verbatim") dns-server, dns-order
dnsTtlSeconds, dnsNegativeTtlSeconds, dnsTimeoutMs dns-ttl-s, dns-negative-ttl-s, dns-timeout-ms
maxPendingLookupsPerIP max-pending-lookups-per-ip
bufferRemainingLength, maxMessageSize buffer-remaining, max-message-size
wsWriteHighWater, uploadWindow ws-write-high-water, upload-window
streamQueueMax, connQueueMax, serverQueueMax, serverQueueMaxPerIP stream-queue-max, conn-queue-max, server-queue-max, server-queue-max-per-ip
socketBufferSize, clientRecvBuffer, listenBacklog socket-buffer-size, client-recv-buffer, listen-backlog
connectTimeoutMs, familyFallbackMs connect-timeout-ms, family-fallback-ms
handshakeTimeoutSeconds handshake-timeout-ms (the wrapper multiplies by 1000)
clientWriteTimeoutSeconds, idleTimeoutSeconds client-write-timeout-s, idle-timeout-s
resolverThreads, busyPollUs, tcpNoDelay, tcpQuickAck resolver-threads, busy-poll-us, tcp-nodelay, tcp-quickack
nonWSResponse, serveWebclient, webclientWispUrl non-ws-response, serve-webclient, webclient-wisp-url
webTransport (true, or an object of the keys below) webtransport
webTransport.host, .port, .url webtransport-host, webtransport-port, webtransport-url
webTransport.certFile, .keyFile, .resetKeyFile webtransport-cert, webtransport-key, webtransport-reset-key-file
webTransport.idleTimeoutSeconds, .maxHandshakes, .retryThreshold webtransport-idle-timeout-s, webtransport-max-handshakes, webtransport-retry-threshold
webTransport.congestionControl ("bbr", "bbr2", "newreno") webtransport-congestion-control

Filter lists take arrays or objects (an object is read as its keys). Ports are numbers, "8000-8999" strings or [low, high] pairs. A hostname *.example.com matches subdomains.

idleTimeoutSeconds (0, off) closes a connection that has no open stream and whose client has sent nothing for that long, with WebSocket code 1001. What the server sends does not count, and a connection with a stream open is never closed for it.

dnsServers entries are IP addresses with an optional port: 1.1.1.1, 1.1.1.1:53 or [2606:4700:4700::1111]:53. Anything else, a name or an IPv6 address without brackets, keeps the server from starting, and start() rejects with the server's message.

passwordUsers is an object of user to password. A user name is 1 to 63 bytes without : or control characters, a password 1 to 127 bytes on one line; a value starting with $ is a crypt(3) hash. passwordAuth defaults to true when passwordUsers has entries, and false ignores them.

Server keys with no option here: proxy-only-to, proxy-client-key, proxy-client-key-secret, udp-warp-marks, udp-warp-state, udp-warp-state-max-age-s, udp-warp-fallback, tcp-warp, tcp-warp-fallback, warp-bypass-host (a policyFile may carry warp-bypass-host lines), webtransport-cert-dir, webtransport-path and webtransport-lanes. They are for an edge that runs the binary under its own service manager (see Proxies and WARP); run holywisp --config directly for those.

These wispurr options are accepted, do nothing, and are named in a warning at start(): tcpBufferSize, pendingQueueSize, dnsMethod, websocketPermessageDeflate, staticDir.

The egress defaults refuse every address that is not public. allowLoopbackIPs and allowPrivateIPs let every client reach the machine and the network the app runs on. Leave them off unless that is the point.

Where secrets go

Passwords, the proxy URL (it may hold credentials) and the per-start proxy secret are written to a file of mode 0600 in a fresh directory under os.tmpdir(), passed as --config, and deleted once the server is up or has failed to start. Everything else is passed as --key=value flags, which any local user can see in the process list. A server message that quotes one of those values has it replaced by [redacted] in the log and in the Error. On Windows the file is protected by the temporary directory's access list instead of a mode.

WebTransport and /webtransport.json

WebTransport is UDP, so route() has no part in it. The browser opens new WebTransport("https://<address>:<port>/") against the server's UDP listener directly, which binds host (127.0.0.1 by default) unless webTransport.host says otherwise. To reach it from another machine, set webTransport.host to an address that machine can reach and open the UDP port.

A page finds the listener by fetching /webtransport.json from the root of the origin its WebSocket goes to. Behind route() that origin is your app's, so the app has to answer it. routeRequest() does:

const wisp = new holyWisp({ webTransport: { host: "0.0.0.0" } });
await wisp.start();

const server = createServer((req, res) => {
	if (wisp.routeRequest(req, res)) return;
	// ... the app
});

As Express middleware:

app.use((req, res, next) => {
	if (!wisp.routeRequest(req, res)) next();
});

It fetches the server's own description and passes it on with Cache-Control: no-store and Access-Control-Allow-Origin: *. When webTransport.url is not set, the server's url is empty. To a page that means "this host over HTTPS", which on the app's origin would be the app's port, so the wrapper puts the listener's address there instead. A run with webTransport: true on loopback answered:

{"url":"https://127.0.0.1:45859/","hashes":[{"algorithm":"sha-256","value":"xa/7oiNxEN3968oPKQHG88NDMZrzcJHNLmbNr1vqcd0="}]}

With a wildcard webTransport.host (0.0.0.0 or ::), the host name of the request is used. Methods other than GET and HEAD get 405, a stopped server 503, and a failed fetch 502. Nothing of the incoming request is sent to the server. Certificates, hashes and their rotation are on WebTransport.

Vite

import { holyWispVite } from "holywisp/vite";

export default {
	plugins: [holyWispVite({ path: "/wisp/", config: { logLevel: "info" } })],
};
Option Default Meaning
path (required) A path prefix, or a function of the request that returns true for upgrades to route.
config {} The holyWisp options.
workers 1 Worker threads; 0 is one per CPU.
apply "both" "serve", "preview" or "both": which Vite servers get a relay.

The plugin starts a server when Vite's dev or preview server starts, routes matching upgrades with route(), and stops it when Vite's HTTP server closes. With config.webTransport it also answers /webtransport.json through routeRequest(). In Vite's middleware mode there is no HTTP server to attach to; the plugin logs a warning, and you call route() from your own server.

Restarts and shutdown

A server that exits without stop() or kill() being called (a crash, the OOM killer, a stray kill) is started again with the same worker count, on the same port if that is still free (the next free one above it otherwise). The first attempt is 100 ms after the exit, the wait doubles up to 5 s while it keeps dying, and it drops back to 100 ms once a server has stayed up for 10 s. During the gap isRunning is false and route() answers 503; connections that were open are gone. autoRestart: false turns this off, and the instance is then stopped and can be started again.

The server does not outlive the Node process:

  • On a normal exit, and on SIGINT, SIGTERM or SIGHUP, the wrapper stops its servers. If your code has its own handler for that signal, the wrapper leaves the decision to it.
  • When Node is killed outright (kill -9, the OOM killer, Task Manager), no handler runs. The server is started with stop-on-stdin-eof and a pipe as its stdin that nothing writes to. When Node dies the kernel closes the pipe and the server shuts down by itself.

stop-on-stdin-eof is also how stop() asks for a shutdown on Windows, which has no SIGTERM. Do not use it when you run the binary yourself with a stdin that is /dev/null or closed: the server would stop as soon as it was up.

Logs

The wrapper writes its own messages and every line the server writes to stderr to standard output via console.log, prefixed [holyWisp]: and coloured by level when stdout is a terminal (NO_COLOR turns colour off, FORCE_COLOR forces it). From a run with logLevel: "info", where the server was killed and came back:

[holyWisp]: server: listening on 127.0.0.1:45859 with 2 workers, flood protection on, reputation on
[holyWisp]: listening on 127.0.0.1:45859, 2 worker(s)
[holyWisp]: filter: 127.0.0.1: blocked www.example.net:80
[holyWisp]: server exited with code null, signal SIGKILL, unasked
[holyWisp]: restarting the server in 100 ms
[holyWisp]: the server is back on port 45859

The server's lines keep the level they were written at; a line that is not a log line (a crash before logging started) is shown as an error.

Platforms

Platform Binary
linux-x64, linux-arm64 Included. Statically linked against musl, so it runs on glibc and Alpine alike.
darwin-x64, darwin-arm64 Included, for macOS 13 and newer. A development port.
win32-x64, win32-arm64 Included, for Windows 10 and newer. A development port.

Production is Linux. The macOS and Windows builds run the same code over kqueue and Winsock's select, copy payloads where Linux uses splice, and have their workers share one listening socket. On Windows start() refuses enableTwisp (no pseudo-terminal) and a hashed passwordUsers value (no crypt), with the server's own message. On macOS it refuses a $id$ hash ($5$, $6$, $y$, $2b$) the same way, because macOS's crypt knows only DES; use plain passwords while developing on a Mac. The Linux binaries' musl crypt knows $1$, $2a$/$2b$, $5$ and $6$ but not yescrypt ($y$), and a $y$ hash there is accepted at start and never matches. Under WSL 2 the Linux binaries work with neither limit.

For any other platform, or a build of your own, point binary (or $HOLYWISP_BIN) at a holywisp executable. It must know trusted-proxy-secret (holywisp --help lists it); an older build fails to start with unknown option.

Building the package

From the repository root, with zig on the PATH (pip install ziglang provides it):

make npm        # the six binaries with zig, then tsc -> node/bin, node/dist
make npm-test   # the wrapper's tests against the tree's release build
cd node && npm pack

More on the build targets is on Building from source.

Clone this wiki locally