API Reference – WireGuard Utils
Skip to content

API Reference

Complete reference for all functions available in @kriper0nind/wg-utils.

Configuration Management

parse(configText: string)

Parses a WireGuard configuration file into a JavaScript object.

Parameters:
  • configText (string): Raw configuration file content

Returns: object - Configuration object with Interface and Peers properties

Example:
import { parse } from "@kriper0nind/wg-utils"
 
const configContent = `[Interface]
PrivateKey = server-private-key
Address = 10.0.0.1/24
 
[Peer]
PublicKey = client-public-key
AllowedIPs = 10.0.0.2/32`
 
const config = parse(configContent)
console.log(config.Interface.Address) // "10.0.0.1/24"

stringify(config: object)

Converts a configuration object back into WireGuard configuration format.

Parameters:
  • config (object): Configuration object with Interface and Peers properties

Returns: string - WireGuard configuration file content

Example:
import { stringify } from "@kriper0nind/wg-utils"
 
const config = {
  Interface: {
    PrivateKey: "server-private-key",
    Address: "10.0.0.1/24"
  },
  Peers: []
}
 
const configText = stringify(config)

Key Management

generateKeys(options?: object)

Generates a new WireGuard key pair.

Parameters:
  • options (object, optional): Configuration options
    • privateKeyPath (string, optional): Path to save private key
    • publicKeyPath (string, optional): Path to save public key

Returns: Promise<{publicKey: string, privateKey: string}>

Example:
import { generateKeys } from "@kriper0nind/wg-utils"
 
const keys = await generateKeys()
console.log(keys.publicKey)  // Generated public key
console.log(keys.privateKey) // Generated private key

getPubKey(filepath: string)

Extracts the public key from a configuration file's private key.

Parameters:
  • filepath (string): Path to the WireGuard configuration file

Returns: Promise<{publicKey: string}>

Example:
import { getPubKey } from "@kriper0nind/wg-utils"
 
const result = await getPubKey("/etc/wireguard/wg0.conf")
console.log(result.publicKey)

Configuration Creation

initConf(filepath: string, options: object)

Creates an initial WireGuard server configuration.

Parameters:
  • filepath (string): Path where to save the configuration file
  • options (object): Configuration options
    • privateKey (string): Server's private key
    • port (number, optional): Listening port (default: 51820)
    • ip (string, optional): Server IP address (default: "10.0.0.1")
    • interface (string, optional): Network interface for NAT (default: "eth0")

Returns: Promise<void>

Example:
import { initConf, generateKeys } from "@kriper0nind/wg-utils"
 
const keys = await generateKeys()
await initConf("/etc/wireguard/wg0.conf", {
  privateKey: keys.privateKey,
  port: 51820,
  ip: "10.0.0.1",
  interface: "eth0"
})

Peer Management

addPeer(filepath: string, options: object)

Adds a new peer to a WireGuard configuration with automatic IP assignment.

Parameters:
  • filepath (string): Path to the WireGuard configuration file
  • options (object): Peer configuration
    • publicKey (string): Peer's public key

Returns: Promise<{ip: string}> - Assigned IP address

Example:
import { addPeer, generateKeys } from "@kriper0nind/wg-utils"
 
const clientKeys = await generateKeys()
const result = await addPeer("/etc/wireguard/wg0.conf", {
  publicKey: clientKeys.publicKey
})
console.log(`Client IP: ${result.ip}`) // "10.0.0.2"

deletePeer(filepath: string, where: object)

Removes a peer from a WireGuard configuration.

Parameters:
  • filepath (string): Path to the WireGuard configuration file
  • where (object): Identification criteria
    • publicKey (string): Public key of the peer to remove

Returns: Promise<void>

Example:
import { deletePeer } from "@kriper0nind/wg-utils"
 
await deletePeer("/etc/wireguard/wg0.conf", {
  publicKey: "client-public-key-to-remove"
})

Interface Control

up(iface: string)

Starts a WireGuard interface.

Parameters:
  • iface (string): Interface name (e.g., "wg0")

Returns: Promise<void>

Example:
import { up } from "@kriper0nind/wg-utils"
 
await up("wg0")
console.log("WireGuard interface started")

down(iface: string)

Stops a WireGuard interface.

Parameters:
  • iface (string): Interface name (e.g., "wg0")

Returns: Promise<void>

Example:
import { down } from "@kriper0nind/wg-utils"
 
await down("wg0")
console.log("WireGuard interface stopped")

syncConf(iface: string)

Synchronizes a WireGuard interface configuration without restarting the interface.

This function applies configuration changes to a running WireGuard interface by using the wg syncconf command. It reads the current configuration from the interface, strips any wg-quick specific directives, and applies the changes without disrupting existing connections.

Parameters:
  • iface (string): Interface name (e.g., "wg0")

Returns: Promise<void>

Example:
import { syncConf } from "@kriper0nind/wg-utils"
 
// After modifying the configuration file, sync the changes
await syncConf("wg0")
console.log("Configuration synchronized")

Note: This function requires the WireGuard interface to be already running. It's particularly useful when you need to apply configuration changes without interrupting active VPN connections.

getLatestHandshake(iface: string)

Retrieves the latest handshake information for all peers on a WireGuard interface.

This function provides detailed connection information including handshake timestamps, transfer statistics, and peer endpoints. It's useful for monitoring VPN connections, debugging connectivity issues, and tracking peer activity.

Parameters:
  • iface (string): Interface name (e.g., "wg0")

Returns: Promise<HandshakeInfo[]> - Array of handshake information for each peer

Example:
import { getLatestHandshake } from "@kriper0nind/wg-utils"
 
const handshakes = await getLatestHandshake("wg0")
console.log("Active peers:", handshakes.length)
 
handshakes.forEach(peer => {
  console.log(`Peer ${peer.publicKey}:`)
  console.log(`  Latest handshake: ${peer.latestHandshake}`)
  console.log(`  Transfer: ${peer.transfer}`)
  console.log(`  Endpoint: ${peer.endpoint}`)
})
HandshakeInfo Interface:
interface HandshakeInfo {
  publicKey: string
  handshake?: string
  endpoint?: string
  allowedIps?: string
  latestHandshake?: string
  transfer?: string
}

Installation & Setup

checkWg()

Checks if WireGuard tools are installed and available.

Returns: Promise<boolean> - true if WireGuard is available, false otherwise

Example:
import { checkWg } from "@kriper0nind/wg-utils"
 
const isInstalled = await checkWg()
if (isInstalled) {
  console.log("WireGuard is ready")
} else {
  console.log("WireGuard not installed")
}

requireWg()

Checks if WireGuard tools are installed and throws an error if not.

Returns: Promise<void>

Throws: Error with installation instructions if WireGuard is not found

Example:
import { requireWg } from "@kriper0nind/wg-utils"
 
try {
  await requireWg()
  console.log("WireGuard is ready")
} catch (error) {
  console.error(error.message)
}

installWg(options?: object)

Installs WireGuard tools on the current platform with automatic detection.

Parameters:
  • options (object, optional): Installation options
    • force (boolean, optional): Force installation even if already installed (default: false)
    • silent (boolean, optional): Suppress package manager output (default: false)

Returns: Promise<void>

Example:
import { installWg } from "@kriper0nind/wg-utils"
 
// Basic installation
await installWg()
 
// Silent installation
await installWg({ silent: true })
 
// Force reinstall
await installWg({ force: true })

getInstallInstructions()

Gets platform-specific installation instructions without installing.

Returns: Promise<object> - Platform info and installation command

Example:
import { getInstallInstructions } from "@kriper0nind/wg-utils"
 
const instructions = await getInstallInstructions()
if (instructions.supported) {
  console.log(`Run: ${instructions.command}`)
} else {
  console.log("Manual installation required")
}

Error Handling

All functions may throw errors in the following scenarios:

  • File operations: ENOENT for missing files, EACCES for permission denied
  • WireGuard operations: Invalid keys, interface already exists, etc.
  • Configuration parsing: Malformed configuration files
  • System operations: Missing WireGuard tools, insufficient privileges
Example error handling:
try {
  await addPeer("/etc/wireguard/wg0.conf", {
    publicKey: "invalid-key"
  })
} catch (error) {
  if (error.code === 'ENOENT') {
    console.error("Configuration file not found")
  } else if (error.message.includes('Invalid key')) {
    console.error("Invalid public key format")
  } else {
    console.error("Unexpected error:", error.message)
  }
}

Type Definitions

interface KeyPair {
  publicKey: string
  privateKey: string
}
 
interface InitConfOptions {
  privateKey: string
  port?: number
  ip?: string
  interface?: string
}
 
interface AddPeerOptions {
  publicKey: string
}
 
interface DeletePeerOptions {
  publicKey: string
}
 
interface GetPubKeyResult {
  publicKey: string
}
 
interface AddPeerResult {
  ip: string
}
 
interface InstallWgOptions {
  force?: boolean
  silent?: boolean
}
 
interface InstallInstructions {
  platform: string
  packageManager?: string
  command?: string
  name?: string
  supported: boolean
}

Requirements

  • Node.js 16 or higher
  • WireGuard installed on the system
  • Root/sudo privileges for interface management
  • iptables installed for NAT functionality