wireguard-js
v1.0.0
Published
Pure-JavaScript WireGuard VPN client. No CGo, no kernel drivers, no root required. Bun-native with Node.js fallback.
Maintainers
Readme
✨ Features
🛡️ Full WireGuard Protocol
- Noise IKpsk2 Handshake — Complete cryptographic handshake per the WireGuard spec
- Curve25519 DH — Elliptic-curve Diffie-Hellman via Node.js native
crypto - ChaCha20-Poly1305 AEAD — Pure-JS implementation (RFC 8439), compatible with Bun
- BLAKE2s-256 & BLAKE2s-128 — Manual RFC 7693 implementation (keyed and unkeyed)
- KDF1 / KDF2 / KDF3 — HMAC-BLAKE2s-based key derivation functions
- TAI64N Timestamps — Replay protection with monotonic timestamps
- Preshared Key (PSK) — Optional additional symmetric-key security layer
- MAC1 & MAC2 — DoS protection via BLAKE2s-128 keyed mode
- Auto-reconnect — Dead-peer detection + automatic re-handshake
🌐 DNS-over-HTTPS Resolver
- Multi-provider with failover — Cloudflare, Google, Quad9
- Protocol control —
auto(fetch/ALPN),h1(HTTPS),h2(HTTP/2) - TLS version pinning — Force TLS 1.1 / 1.2 / 1.3
- In-memory cache — Respects DNS TTL, configurable max TTL
- Drop-in replacement —
dohLookup()mirrorsdns/promises.lookup()
🔌 Userspace TCP/IP Stack
- Multiplexed connections — Multiple concurrent TCP sockets over one tunnel
- Full 3-way handshake — SYN → SYN-ACK → ACK
- MSS chunking — Automatic segmentation for large writes
- Graceful FIN + RST handling — Proper half-close and force-close
- EventEmitter API —
data,end,close,errorevents
🚇 HTTP CONNECT Proxy
- Local CONNECT proxy — Routes any HTTP(S) client through WireGuard
- DoH resolution — Resolves target hostnames inside the proxy
- Configurable port — Picks a random port by default (
0) - Singleton manager —
WireGuardManagermanages the full lifecycle
📦 Installation
# Clone and install
git clone https://github.com/galang-rs/bun-wiregaurd.git
cd bun-wiregaurd
npm install # or: bun install
# Use as a local dependency
npm install ../path/to/wireguard-js🚀 Quick Start
import { connect, readConfigFile } from 'wireguard-js';
const opts = readConfigFile('./wireguard.conf');
const tun = await connect(opts);
console.log('Connected:', tun.tunnelInfo());
// { ip: '172.16.0.2', netMask: '32', gw: 'engage.cloudflareclient.com:2408', mtu: 1420 }
// Receive decrypted IP packets from VPN
tun.on('data', (ipPacket) => {
const version = (ipPacket[0] >> 4) & 0xf;
console.log(`IPv${version} packet: ${ipPacket.length} bytes`);
});
// Send a raw IP packet into the VPN
tun.write(ipPacket);
// Disconnect
tun.close();Run the Example
node example.js path/to/wireguard.conf
# or
bun example.js path/to/wireguard.conf📖 API Reference
connect(opts, [logger]) → Promise<WireGuardTunnel>
Connect to a WireGuard peer and return a tunnel instance.
import { connect, readConfigFile } from 'wireguard-js';
const opts = readConfigFile('./wireguard.conf');
const tun = await connect(opts, {
info: (...a) => console.log('[WG]', ...a),
debug: () => {},
warn: (...a) => console.warn('[WG]', ...a),
error: (...a) => console.error('[WG]', ...a),
});WireGuardTunnel
| Method / Property | Description |
|-------------------------|------------------------------------------------------|
| tunnelInfo() | { ip, netMask, gw, mtu, dns } |
| write(ipPacket) | Send a raw IP packet through the VPN |
| close() | Permanently close the tunnel |
| on('data', fn) | Receive decrypted IP packets (Buffer) |
| on('connected', fn) | Fired on initial connect and successful reconnects |
| on('reconnecting', fn)| Fired when auto-reconnect starts (attemptNumber) |
| on('close', fn) | Fired when tunnel is permanently closed |
| on('error', fn) | Non-fatal errors |
readConfigFile(filePath) / parseConfigString(content)
Parse a standard WireGuard .conf file.
import { readConfigFile } from 'wireguard-js';
const opts = readConfigFile('./wireguard.conf');
// opts.privateKey, opts.address, opts.peer.publicKey, opts.peer.endpoint, ...WireGuardManager (Singleton)
Manages tunnel + TCP stack + HTTP CONNECT proxy as a single lifecycle unit.
import { WireGuardManager } from 'wireguard-js/manager';
await WireGuardManager.init('./wireguard.conf');
console.log(WireGuardManager.proxyUrl); // 'http://127.0.0.1:PORT'
console.log(WireGuardManager.exitIP); // '162.159.x.x'
console.log(WireGuardManager.isActive); // true
const bypass = WireGuardManager.shouldBypass(url); // true for CDN image URLs
WireGuardManager.destroy();DoHResolver / dohLookup
DNS-over-HTTPS resolver with provider failover and caching.
import { dohLookup, DoHResolver } from 'wireguard-js/dns';
// Simple lookup
const { address } = await dohLookup('example.com', { family: 4 });
// With full control
const resolver = new DoHResolver({
protocol: 'h2', // 'auto' | 'h1' | 'h2'
tlsVersion: '1.3', // '1.1' | '1.2' | '1.3' | null
timeout: 5000,
});
const ip = await resolver.resolve('example.com', 4);TcpStack
Multiplexed userspace TCP connections over the raw WireGuard tunnel.
import { TcpStack } from 'wireguard-js/tcpStack';
const stack = new TcpStack(tun, logger);
const conn = await stack.connect('93.184.216.34', 80);
conn.write('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
conn.on('data', (buf) => console.log(buf.toString()));
conn.on('close', () => console.log('Connection closed'));
stack.destroy(); // Close all connections🏗️ Project Structure
wireguard-js/
├── index.js ← Public npm entry point (re-exports everything)
├── package.json
├── .gitignore
├── example.js ← Runnable demo (replaces test.js)
├── wireguard.conf.example← Example WireGuard config (do NOT commit real keys!)
└── src/
├── config.js ← .conf file parser + key helpers
├── tunnel.js ← WireGuardTunnel — main tunnel class
├── manager.js ← WireGuardManager singleton
├── core/
│ ├── crypto.js ← BLAKE2s, ChaCha20-Poly1305, X25519, KDF1/2/3
│ ├── message.js ← Wire format serialization/deserialization
│ └── session.js ← Noise IKpsk2 handshake state machine
└── net/
├── dns.js ← DNS-over-HTTPS resolver (h1/h2/auto, cache, fallback)
├── tcpStack.js ← Userspace TCP/IP stack (multiplexed connections)
├── ipcheck.js ← Minimal HTTP GET over raw WireGuard tunnel
└── proxy.js ← HTTP CONNECT proxy🔧 WireGuard Config Format
[Interface]
PrivateKey = <base64-encoded-32-byte-private-key>
Address = 172.16.0.2/32
DNS = 1.1.1.1, 8.8.8.8
MTU = 1420
[Peer]
PublicKey = <base64-encoded-32-byte-public-key>
PresharedKey = <base64-encoded-32-byte-preshared-key> # optional
Endpoint = engage.cloudflareclient.com:2408
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 25⚠️ Never commit real
.conffiles to Git! They contain private keys.
The.gitignorein this repo already excludes*.confandwireguard.conf.
🔗 Related Projects
| Project | Language | Description | |---------|----------|-------------| | galang-rs/wireguard | Go | Original Go implementation this was ported from | | WireGuard | C / Kernel | Official WireGuard kernel module |
📦 Dependencies
| Package | Purpose |
|---------|---------|
| node:crypto | X25519 DH, random bytes |
| node:http2 | H2 DoH transport |
| node:https | H1 DoH transport |
| node:dgram | UDP socket (Node.js fallback) |
| node:net | TCP server for local proxy |
| events | EventEmitter |
Zero npm dependencies. Only Node.js built-ins.
📄 License
MIT License
Copyright (c) 2026 Galang Reisduanto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.Additional Terms:
- Attribution — If you use this in a product, a mention in your docs or "About" section is appreciated but not required.
- Non-Endorsement — The name "galang-rs" or "Galang Reisduanto" may not be used to endorse or promote derived products without prior written permission.
- Good Faith — This software is shared for the open-source community. Commercial use is permitted and encouraged.
📬 Contact & Feature Requests
☕ Support & Donate
If this project helped you, consider buying me a coffee!
