feat(new tool): Wireguard Config Generator

Fix #1536
This commit is contained in:
ShareVB committed 2025-08-21 15:25:44 +02:00
1 parent e2f6a8299c
commit 241dd6f9fb
9 files changed
+1083

No files matched your search

+3
View File
@@ -204,6 +204,7 @@
"lodash.defaultsdeep": "^4.6.1",
"lodash.flattendeep": "^4.4.0",
"lodash.last": "^3.0.0",
"lodash.mergewith": "^4.6.2",
"long": "^5.3.1",
"lorem-ipsum-japanese": "^1.0.1",
"luhn-js": "^1.1.2",
@@ -256,6 +257,7 @@
"qrcode": "^1.5.4",
"qrcode-parser": "^2.1.3",
"qrcode-terminal-nooctal": "^0.12.1",
"qrcode-vue3": "^1.7.1",
"quicktype-core": "^23.1.3",
"randexp": "^0.5.3",
"regex": "^4.4.0",
@@ -342,6 +344,7 @@
"@types/lodash.defaultsdeep": "^4.6.9",
"@types/lodash.flattendeep": "^4.4.9",
"@types/lodash.last": "^3.0.9",
"@types/lodash.mergewith": "^4.6.9",
"@types/luxon": "^3.4.2",
"@types/markdown-it": "^13.0.9",
"@types/memorystream": "^0.3.4",
+25
View File
@@ -500,6 +500,9 @@ dependencies:
lodash.last:
specifier: ^3.0.0
version: 3.0.0
lodash.mergewith:
specifier: ^4.6.2
version: 4.6.2
long:
specifier: ^5.3.1
version: 5.3.1
@@ -656,6 +659,9 @@ dependencies:
qrcode-terminal-nooctal:
specifier: ^0.12.1
version: 0.12.1
qrcode-vue3:
specifier: ^1.7.1
version: 1.7.1
quicktype-core:
specifier: ^23.1.3
version: 23.1.3
@@ -910,6 +916,9 @@ devDependencies:
'@types/lodash.last':
specifier: ^3.0.9
version: 3.0.9
'@types/lodash.mergewith':
specifier: ^4.6.9
version: 4.6.9
'@types/luxon':
specifier: ^3.4.2
version: 3.4.2
@@ -6647,6 +6656,12 @@ packages:
'@types/lodash': 4.17.20
dev: true
/@types/lodash.mergewith@4.6.9:
resolution: {integrity: sha512-fgkoCAOF47K7sxrQ7Mlud2TH023itugZs2bUg8h/KzT+BnZNrR2jAOmaokbLunHNnobXVWOezAeNn/lZqwxkcw==}
dependencies:
'@types/lodash': 4.17.20
dev: true
/@types/lodash@4.17.20:
resolution: {integrity: sha512-H3MHACvFUEiujabxhaI/ImO6gUrd8oOurg7LQtS7mbwIXA/cUqWrvBsaeJ23aZEPk1TAYkurjfMbSELfoCXlGA==}
@@ -13676,6 +13691,10 @@ packages:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
dev: true
/lodash.mergewith@4.6.2:
resolution: {integrity: sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==}
dev: false
/lodash.sortby@4.7.0:
resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==}
dev: true
@@ -15769,6 +15788,12 @@ packages:
hasBin: true
dev: false
/qrcode-vue3@1.7.1:
resolution: {integrity: sha512-Xa82NslFJUqsnQbLtc1qO+xPEOeFaTRxktg3ugRd2Pk116kta1X+7GLSEPQj9gor8jWVyfmLmhYZHuANnRZoLQ==}
dependencies:
qrcode-generator: 1.4.4
dev: false
/qrcode@1.5.4:
resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==}
engines: {node: '>=10.13.0'}
@@ -0,0 +1,13 @@
import { Link } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Wireguard Config Generator',
path: '/wireguard-config-generator',
description: 'Generate Wireguard Server and Clients configuration files',
keywords: ['wireguard', 'config', 'generator'],
component: () => import('./wireguard-config-generator.vue'),
icon: Link,
createdAt: new Date('2025-08-15'),
category: 'Network',
});
@@ -0,0 +1,137 @@
import mergeWith from 'lodash.mergewith';
import { generateConfigString, parseConfigString } from './utils/configParser';
import type { WgConfigObject, WgConfigPeer } from './types/WgConfigObject';
import { generateKeyPair } from './utils/generateKeyPair';
interface GenerateKeysOptions {
/** Also create a preshared key */
preSharedKey?: boolean
/**
* Overwrite this object's private key if it already exists
*
* If this is not set to true, a new public key will be generated from the existing private key if
* the private key exists.
*/
overwrite?: boolean
}
/** A Javascript object representation of a WireGuard config file with some extras */
export class WgConfig implements WgConfigObject {
/** Defines the VPN settings for the local node. */
wgInterface: WgConfigObject['wgInterface'] = {};
/** An array of VPN settings for remote peers */
peers: WgConfigObject['peers'];
/** A place to keep the public key for this node (it's not saved in the WireGuard config) */
publicKey: WgConfigObject['publicKey'];
/** A place to keep the pre-shared key for this node (it's not saved in the WireGuard config) */
preSharedKey: WgConfigObject['preSharedKey'];
/** A place to keep the endpoint for this node (it's not saved in the WireGuard config) */
endpoint: WgConfigObject['endpoint'];
/** A place to keep the client AllowedIPs for this node (it's not saved in the WireGuard config) */
clientsAllowedIps: WgConfigObject['clientsAllowedIps'];
/** creates a new WgConfig */
constructor(init: Partial<WgConfigObject>) {
if (init?.wgInterface) {
this.wgInterface = init.wgInterface;
}
this.peers = init?.peers || [];
this.preSharedKey = init?.preSharedKey;
this.publicKey = init?.publicKey;
}
/** Return a string akin to a WireGuard config file from this WgConfig object */
toString() {
return generateConfigString(this);
}
/** JSON.stringify this WgConfig object */
toJson() {
return JSON.stringify(this);
}
/** Parse a WireGuard config file in the form of a string into this WgConfig object */
parse(configAsString: string) {
const parsedObj = parseConfigString(configAsString);
Object.assign(this, parsedObj);
}
/** Generate a public/private key pair for this WgConfig object */
generateKeys(opts?: GenerateKeysOptions) {
const overwrite = opts?.overwrite;
const privateKey = overwrite ? undefined : this.wgInterface?.privateKey;
const keys = generateKeyPair({ privateKey, preSharedKey: opts?.preSharedKey ?? false });
this.publicKey = keys.publicKey;
this.wgInterface.privateKey = keys.privateKey;
this.preSharedKey = keys.preSharedKey;
return keys;
}
/**
* Add a peer to the peers for this WgConfig.
*
* If the peer already exists (found by public key) then it will be updated by merging the
* existing with the new. The allowedIps will be replaced by the new peer's allowedIps unless
* { mergeAllowedIps: true } is passed in as settings
*/
addPeer(peer: WgConfigPeer, settings?: { mergeAllowedIps?: boolean }) {
const mergeAllowedIps = settings?.mergeAllowedIps;
if (!this.peers) {
this.peers = [];
}
// check if peer exists by public key
const i = this.peers.map(x => x.publicKey).indexOf(peer.publicKey);
if (i === -1) {
this.peers.push(peer);
}
else {
mergeWith(this.peers[i], peer, (objValue: any, srcValue: any, key: string) => {
if (key === 'allowedIps' && Array.isArray(objValue) && Array.isArray(srcValue)) {
return mergeAllowedIps ? [...new Set([...objValue, ...srcValue])] : srcValue;
}
});
}
}
/**
* Remove a peer if it exists in the peer array by its public key
*/
removePeer(publicKey: string) {
if (!this.peers) {
this.peers = [];
}
const i = this.peers.map(x => x.publicKey).indexOf(publicKey);
if (i !== -1) {
this.peers.splice(i, 1);
}
}
/** Creates a WfgConfigPeer object from this WgCongig object */
createPeer(settings: WgConfigPeer) {
const keys = generateKeyPair({ privateKey: undefined, preSharedKey: !!this.preSharedKey });
const peer: WgConfigPeer = {
privateKey: keys.privateKey,
publicKey: keys.publicKey,
preSharedKey: this.preSharedKey,
endpoint: this.endpoint,
allowedIps: this.clientsAllowedIps,
...settings,
};
return peer;
}
/** Get a peer from the peer array by it's public key */
getPeer(publicKey: string) {
if (!publicKey) {
return undefined;
}
if (!this.peers || !this.peers.length) {
return undefined;
}
return this.peers.find(x => x.publicKey === publicKey);
}
clearPeers() {
this.peers = [];
}
}
@@ -0,0 +1,142 @@
/** Defines the VPN settings for the local node. */
export interface WgConfigInterface {
/**
* This is just a standard comment in INI syntax used to help keep track of which config section belongs to which node,
* it's completely ignored by WireGuard and has no effect on VPN behavior.
*/
name?: string
/**
* Defines what address range the local node should route traffic for.
* Depending on whether the node is a simple client joining the VPN subnet, or a bounce server that's relaying traffic
* between multiple clients, this can be set to a single IP of the node itself (specified with CIDR notation),
* e.g. 192.0.2.3/32), or a range of IPv4/IPv6 subnets that the node can route traffic for.
*/
address?: string[]
/**
* When the node is acting as a public bounce server, it should hardcode a port to listen for incoming VPN connections
* from the public internet. Clients not acting as relays should not set this value.
*/
listenPort?: number
/**
* This is the private key for the local node, never shared with other servers.
* All nodes must have a private key set, regardless of whether they are public bounce servers relaying traffic,
* or simple clients joining the VPN.
*/
privateKey?: string
/**
* The DNS server(s) to announce to VPN clients via DHCP, most clients will use this server for DNS requests over the VPN,
* but clients can also override this value locally on their nodes
*/
dns?: string[]
/**
* Optionally defines which routing table to use for the WireGuard routes, not necessary to configure for most setups.
* There are two special values:
* -**‘off’**: disables the creation of routes altogether, and
* -**‘auto’**: (the default if omitted) adds routes to the default table and enables special handling of default routes.
*/
table?: string
/**
* Optionally defines the maximum transmission unit (MTU, aka packet/frame size) to use when connecting to the peer,
* not necessary to configure for most setups. The MTU is automatically determined from the endpoint addresses or
* the system default route, which is usually a sane choice.
*/
mtu?: number
/**
* Optionally run bash commands before the interface is brought up.
* These will be added to the config file in order and executed in order. Position 0 in array will be run first.
*/
preUp?: string[]
/**
* Optionally run bash commands after the interface is brought up.
* These will be added to the config file in order and executed in order. Position 0 in array will be run first.
*/
postUp?: string[]
/**
* Optionally run bash commands before the interface is brought down.
* These will be added to the config file in order and executed in order. Position 0 in array will be run first.
*/
preDown?: string[]
/**
* Optionally run bash commands after the interface is brought down.
* These will be added to the config file in order and executed in order. Position 0 in array will be run first.
*/
postDown?: string[]
}
/**
* Defines the VPN settings for a remote peer capable of routing traffic for one or more addresses (itself and/or other peers).
* Peers can be either a public bounce server that relays traffic to other peers, or a directly accessible client via
* LAN/internet that is not behind a NAT and only routes traffic for itself.
*/
export interface WgConfigPeer {
/**
* This is just a standard comment in INI syntax used to help keep track of which config section belongs to which node,
* it's completely ignored by WireGuard and has no effect on VPN behavior.
*/
name?: string
/**
* Defines the publicly accessible address for a remote peer.
* This should be left out for peers behind a NAT or peers that don't have a stable publicly accessible IP:PORT pair.
* Typically, this only needs to be defined on the main bounce server, but it can also be defined on other public nodes with stable IPs.
*/
endpoint?: string
/**
* This defines the IP ranges for which a peer will route traffic.
* On simple clients, this is usually a single address (the VPN address of the simple client itself).
* For bounce servers this will be a range of the IPs or subnets that the relay server is capable of routing traffic for.
*/
allowedIps?: string[]
/**
* This is the public key for the remote node, shareable with all peers. All nodes must have a
* public key set, regardless of whether they are public bounce servers relaying traffic, or simple clients joining the VPN.
*/
publicKey?: string
/**
* The number of seconds between each keep-alive ping.
* If the connection is going from a NAT-ed peer to a public peer, the node behind the NAT must regularly send an outgoing
* ping in order to keep the bidirectional connection alive in the NAT router's connection table.
*/
persistentKeepalive?: number
/**
* A pre-shared key generated on the remote node to improve security.
*/
preSharedKey?: string
/**
* Client Assigned IP
*/
clientAssignedIP?: string
/**
* Client Private Key
*/
privateKey?: string
}
/** Defines the WireGuard config for this node */
export interface WgConfigObject {
/** Defines the VPN settings for the local node. */
wgInterface: WgConfigInterface
/** An array of VPN settings for remote peers */
peers?: WgConfigPeer[]
/**
* A place to keep the public key for this node
* Usefull when saving this config somewhere where you can't generate the public key
*
* Note: the private key for this node should be kept in `interface.privateKey`
*/
publicKey?: string
/**
* A place to keep the preSharedKey key for this node
* Usefull when saving this config somewhere where you need to generate peers in future
*/
preSharedKey?: string
/**
* A place to keep the endpoint key for this node
* Usefull when saving this config somewhere where you need to generate peers in future
*/
endpoint?: string
/**
* A place to keep the client AllowedIPs key for this node
* Usefull when saving this config somewhere where you need to generate peers in future
*/
clientsAllowedIps?: string[]
}
@@ -0,0 +1,259 @@
import type { WgConfigInterface, WgConfigObject, WgConfigPeer } from '../types/WgConfigObject';
interface FindPartInStringOptions {
string: string
part: string
}
/**
* Find a part in the string based on left hand side of '='
* eg:
* string === 'PrivateKey = 123456'
* part === 'PrivateKey'
* return value = ['123456']
* OR
* string === 'PrivateKey = 123456'
* part === 'SomethingElse'
* return value = undefined
*/
function findPartInString({ string, part }: FindPartInStringOptions) {
const parts = string.split('\n');
const wantedParts = parts.filter(x => x.includes(part));
if (!wantedParts.length) {
return undefined;
}
const values = wantedParts
.map(x => x.match(/((?<==).)(.+$)/gm)?.[0]?.trim())
.filter(x => x !== undefined) as string[];
if (!values.length) {
return undefined;
}
return values as [string, ...string[]];
}
/** Generate a string version of the WgConfig suitable for saving to a Wireguard Config file (wg0.conf) */
export function generateConfigString(conf: WgConfigObject): {
server: string
peers: { name: string; config: string }[]
} {
const s: string[] = [];
const { wgInterface, peers, publicKey } = conf;
const { address, privateKey, listenPort, name, dns, mtu, table, preUp, postUp, preDown, postDown } = wgInterface;
// add interface
s.push('[Interface]');
if (name !== undefined) {
s.push(`# Name = ${name}`);
}
if (address !== undefined && address.length) {
s.push(`Address = ${address.join(',')}`);
}
if (privateKey) {
s.push(`PrivateKey = ${privateKey}`);
}
if (publicKey) {
s.push(`PublicKey = ${publicKey}`);
}
if (listenPort) {
s.push(`ListenPort = ${listenPort}`);
}
if (dns && dns.length) {
s.push(`DNS = ${dns.join(',')}`);
}
if (mtu) {
s.push(`MTU = ${mtu}`);
}
if (table) {
s.push(`Table = ${table}`);
}
if (preUp && preUp.length) {
s.push(preUp.map(x => `PreUp = ${x}`).join('\n'));
}
if (postUp && postUp.length) {
s.push(postUp.map(x => `PostUp = ${x}`).join('\n'));
}
if (preDown && preDown.length) {
s.push(preDown.map(x => `PreDown = ${x}`).join('\n'));
}
if (postDown && postDown.length) {
s.push(postDown.map(x => `PostDown = ${x}`).join('\n'));
}
const peersConfig: Array<{ name: string; config: string }> = [];
// add peers
if (peers?.length) {
peers.forEach((peer) => {
s.push('');
s.push('[Peer]');
if (peer.name) {
s.push(`# Name = ${peer.name}`);
}
if (peer.publicKey) {
s.push(`PublicKey = ${peer.publicKey}`);
}
if (peer.privateKey) {
s.push(`# PrivateKey = ${peer.privateKey}`);
}
if (peer.clientAssignedIP) {
s.push(`AllowedIPs = ${peer.clientAssignedIP}/32`);
}
if (peer.endpoint) {
s.push(`Endpoint = ${peer.endpoint}`);
}
if (peer.preSharedKey) {
s.push(`PresharedKey = ${peer.preSharedKey}`);
}
if (peer.persistentKeepalive) {
s.push(`PersistentKeepalive = ${peer.persistentKeepalive}`);
}
});
peers.forEach((peer) => {
const peerConfig: Array<string> = [];
peerConfig.push('[Interface]');
if (peer.name) {
peerConfig.push(`# Name = ${peer.name}`);
}
if (peer.clientAssignedIP) {
peerConfig.push(`Address = ${peer.clientAssignedIP}/${(address || ['/24'])[0].split('/')[1]}`);
}
if (peer.privateKey) {
peerConfig.push(`PrivateKey = ${peer.privateKey}`);
}
peerConfig.push('');
peerConfig.push('');
peerConfig.push('[Peer]');
if (publicKey) {
peerConfig.push(`PublicKey = ${publicKey}`);
}
if (peer.preSharedKey) {
peerConfig.push(`PresharedKey = ${peer.preSharedKey}`);
}
if (peer.allowedIps && peer.allowedIps.length) {
peerConfig.push(`AllowedIPs = ${peer.allowedIps.join(',')}`);
}
if (peer.endpoint) {
peerConfig.push(`Endpoint = ${peer.endpoint}`);
}
peersConfig.push({ name: peer.name || '', config: peerConfig.join('\n') });
});
}
return {
server: s.join('\n'),
peers: peersConfig,
};
}
/**
* Parse a WireGuard config file (wg0.conf) into a WgConfig object for use in Javascript-land
* If no valid interface is found in the config, it will throw an error
* If a peer in the peers array is invalid, it will throw an error
*/
export function parseConfigString(configString: string) {
const interFaceReg = /\[Interface\][^\[]*/gm;
const peerReg = /\[Peer\][^\[]*/gm;
const interfaces = configString.match(interFaceReg);
const interfaceString = interfaces?.[0];
if (!interfaceString) {
throw new Error(`No interface found in config:\n${configString}`);
}
const maybeAddress = findPartInString({ string: interfaceString, part: 'Address' })?.[0]?.split(',');
const address = maybeAddress ? maybeAddress.filter(x => x !== undefined) as [string, ...string[]] : undefined;
if (!address || !address.length) {
throw new Error(`No address found in config:\n${configString}`);
}
const privateKey = findPartInString({ string: interfaceString, part: 'PrivateKey' })?.[0];
if (!privateKey) {
throw new Error(`No privateKey found in config:\n${configString}`);
}
const maybeListenPort = findPartInString({ string: interfaceString, part: 'ListenPort' })?.[0];
const listenPort = maybeListenPort ? Number.parseInt(maybeListenPort) : undefined;
const maybeMTU = findPartInString({ string: interfaceString, part: 'MTU' })?.[0];
const mtu = maybeMTU ? Number.parseInt(maybeMTU) : undefined;
const maybeDns = findPartInString({ string: interfaceString, part: 'DNS' })?.[0]?.split(',').filter(x => x !== undefined);
const dns = maybeDns?.length ? maybeDns : undefined;
const wgInterface: WgConfigInterface = {
// required keys
address,
privateKey,
// optional keys
dns,
listenPort,
mtu,
name: findPartInString({ string: interfaceString, part: 'Name' })?.[0],
table: findPartInString({ string: interfaceString, part: 'Table' })?.[0],
preUp: findPartInString({ string: interfaceString, part: 'PreUp' }),
postUp: findPartInString({ string: interfaceString, part: 'PostUp' }),
preDown: findPartInString({ string: interfaceString, part: 'PreDown' }),
postDown: findPartInString({ string: interfaceString, part: 'PostDown' }),
};
// remove any undefined keys
let key: keyof WgConfigInterface;
for (key in wgInterface) {
if (wgInterface[key] === undefined) {
delete wgInterface[key];
}
}
const peerStrings = configString.match(peerReg);
const peers = !peerStrings
? []
: peerStrings.map((x) => {
if (!x) {
return undefined;
}
const maybeAllowedIps = findPartInString({ string: x, part: 'AllowedIPs' })?.[0]?.split(',');
const allowedIps = maybeAllowedIps ? maybeAllowedIps.filter(y => y !== undefined) as [string, ...string[]] : undefined;
if (!allowedIps || !allowedIps.length) {
throw new Error(`No allowedIps found in peer:\n${x}`);
}
const publicKey = findPartInString({ string: x, part: 'PublicKey' })?.[0];
if (!publicKey) {
throw new Error(`No publicKey found in peer:\n${x}`);
}
const maybePersistentKeepAlive = findPartInString({ string: interfaceString, part: 'PersistentKeepalive' })?.[0];
const persistentKeepalive = maybePersistentKeepAlive ? Number.parseInt(maybePersistentKeepAlive) : undefined;
const peer: WgConfigPeer = {
// required keys
allowedIps,
publicKey,
// optional keys
persistentKeepalive,
name: findPartInString({ string: x, part: 'Name' })?.[0],
endpoint: findPartInString({ string: x, part: 'Endpoint' })?.[0],
preSharedKey: findPartInString({ string: x, part: 'PresharedKey' })?.[0],
};
// remove undefined keys
let peerKey: keyof WgConfigPeer;
for (peerKey in peer) {
if (peer[peerKey] === undefined) {
delete peer[peerKey];
}
}
return peer;
}).filter(x => x !== undefined) as WgConfigPeer[];
const returnVal: Pick<WgConfigObject, 'peers' | 'wgInterface'> = {
wgInterface,
peers,
};
return returnVal;
}
@@ -0,0 +1,36 @@
import type { WgConfigPeer } from '../types/WgConfigObject';
import type { WgConfig } from '../WgConfig';
interface CreatePeerPairsOptions {
/** The config to derive public key from for the peer */
config: WgConfig
/** The peer settings to apply when adding this config as a peer */
peerSettings: Omit<WgConfigPeer, 'publicKey'> | ((args: { thisConfig: WgConfig; peerConfig: WgConfig }) => Omit<WgConfigPeer, 'publicKey'>)
}
/**
* Create peer pairs from more than one WgConfig object.
*
* Will add wgConfigs[0] as a peer in wgConfigs[1] and wgConfigs[1] as a peer in wgConfigs[0] etc.
* Will fail and error if
*/
export function createPeerPairs(pairs: CreatePeerPairsOptions[]) {
for (let i = 0; i < pairs.length; i++) {
const thisConfig = pairs[i];
for (let subI = 0; subI < pairs.length; subI++) {
const peerConfig = pairs[subI];
if (thisConfig.config.publicKey === peerConfig.config.publicKey) {
continue;
}
const peerSettings = typeof peerConfig.peerSettings === 'function'
? peerConfig.peerSettings({ thisConfig: thisConfig.config, peerConfig: peerConfig.config })
: peerConfig.peerSettings;
const thisConfigPreSharedKey = thisConfig.config.preSharedKey;
if (thisConfigPreSharedKey) {
peerSettings.preSharedKey = thisConfigPreSharedKey;
}
const peer = peerConfig.config.createPeer(peerSettings);
thisConfig.config.addPeer(peer, { mergeAllowedIps: false });
}
}
}
@@ -0,0 +1,209 @@
/*! SPDX-License-Identifier: GPL-2.0
*
* Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
*/
import { Base64 } from 'js-base64';
function gf(init?: Array<number>) {
const r = new Float64Array(16);
if (init) {
for (let i = 0; i < init.length; ++i) {
r[i] = init[i];
}
}
return r;
}
function pack(o: Uint8Array, n: Float64Array) {
let b;
const m = gf();
const t = gf();
for (let i = 0; i < 16; ++i) {
t[i] = n[i];
}
carry(t);
carry(t);
carry(t);
for (let j = 0; j < 2; ++j) {
m[0] = t[0] - 0xFFED;
for (let i = 1; i < 15; ++i) {
m[i] = t[i] - 0xFFFF - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xFFFF;
}
m[15] = t[15] - 0x7FFF - ((m[14] >> 16) & 1);
b = (m[15] >> 16) & 1;
m[14] &= 0xFFFF;
cswap(t, m, 1 - b);
}
for (let i = 0; i < 16; ++i) {
o[2 * i] = t[i] & 0xFF;
o[2 * i + 1] = t[i] >> 8;
}
}
function carry(o: Float64Array) {
// let c;
for (let i = 0; i < 16; ++i) {
o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
o[i] &= 0xFFFF;
}
}
function cswap(p: Float64Array, q: Float64Array, b: number) {
let t;
const c = ~(b - 1);
for (let i = 0; i < 16; ++i) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function add(o: Float64Array, a: Float64Array, b: Float64Array) {
for (let i = 0; i < 16; ++i) {
o[i] = (a[i] + b[i]) | 0;
}
}
function subtract(o: Float64Array, a: Float64Array, b: Float64Array) {
for (let i = 0; i < 16; ++i) {
o[i] = (a[i] - b[i]) | 0;
}
}
function multmod(o: Float64Array, a: Float64Array, b: Float64Array) {
const t = new Float64Array(31);
for (let i = 0; i < 16; ++i) {
for (let j = 0; j < 16; ++j) {
t[i + j] += a[i] * b[j];
}
}
for (let i = 0; i < 15; ++i) {
t[i] += 38 * t[i + 16];
}
for (let i = 0; i < 16; ++i) {
o[i] = t[i];
}
carry(o);
carry(o);
}
function invert(o: Float64Array, i: Float64Array) {
const c = gf();
for (let a = 0; a < 16; ++a) {
c[a] = i[a];
}
for (let a = 253; a >= 0; --a) {
multmod(c, c, c);
if (a !== 2 && a !== 4) {
multmod(c, c, i);
}
}
for (let a = 0; a < 16; ++a) {
o[a] = c[a];
}
}
function clamp(z: Uint8Array) {
z[31] = (z[31] & 127) | 64;
z[0] &= 248;
}
function generatePublicKey(privateKey: Uint8Array) {
let r;
const z = new Uint8Array(32);
const a = gf([1]);
const b = gf([9]);
const c = gf();
const d = gf([1]);
const e = gf();
const f = gf();
const _121665 = gf([0xDB41, 1]);
const _9 = gf([9]);
for (let i = 0; i < 32; ++i) {
z[i] = privateKey[i];
}
clamp(z);
for (let i = 254; i >= 0; --i) {
r = (z[i >>> 3] >>> (i & 7)) & 1;
cswap(a, b, r);
cswap(c, d, r);
add(e, a, c);
subtract(a, a, c);
add(c, b, d);
subtract(b, b, d);
multmod(d, e, e);
multmod(f, a, a);
multmod(a, c, a);
multmod(c, b, e);
add(e, a, c);
subtract(a, a, c);
multmod(b, a, a);
subtract(c, d, f);
multmod(a, c, _121665);
add(a, a, d);
multmod(c, c, a);
multmod(a, d, f);
multmod(d, b, _9);
multmod(b, e, e);
cswap(a, b, r);
cswap(c, d, r);
}
invert(c, c);
multmod(a, a, c);
pack(z, a);
return z;
}
function generatePresharedKey() {
const preSharedKey = new Uint8Array(32);
window.crypto.getRandomValues(preSharedKey);
return preSharedKey;
}
function generatePrivateKey() {
const privateKey = generatePresharedKey();
clamp(privateKey);
return privateKey;
}
// function encodeBase64(dest: Uint8Array, src: Uint8Array) {
// const input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]);
// for (let i = 0; i < 4; ++i) {
// dest[i] = input[i] + 65
// + (((25 - input[i]) >> 8) & 6)
// - (((51 - input[i]) >> 8) & 75)
// - (((61 - input[i]) >> 8) & 15)
// + (((62 - input[i]) >> 8) & 3);
// }
// }
// function keyToBase64(key: Uint8Array) {
// let i;
// const base64 = new Uint8Array(44);
// for (i = 0; i < 32 / 3; ++i) {
// encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
// }
// encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
// base64[43] = 61;
// return String.fromCharCode.apply(null, [...base64]);
// }
export function generateKeyPair({
privateKey = undefined,
preSharedKey = false,
}: {
privateKey: Uint8Array | string | undefined
preSharedKey: boolean
}) {
if (!privateKey) {
privateKey = generatePrivateKey();
}
const privateKeyUint8Array = typeof privateKey === 'string' ? Base64.toUint8Array(privateKey) : privateKey;
const publicKey = generatePublicKey(privateKeyUint8Array);
return {
publicKey: Base64.fromUint8Array(publicKey),
privateKey: Base64.fromUint8Array(privateKeyUint8Array),
preSharedKey: preSharedKey ? Base64.fromUint8Array(generatePresharedKey()) : undefined,
};
}
@@ -0,0 +1,259 @@
<script setup lang="ts">
import { parseCidr } from 'cidr-tools';
import { stringifyIp } from 'ip-bigint';
import QRCodeVue3 from 'qrcode-vue3';
import { WgConfig } from './lib/WgConfig';
import { generateConfigString } from './lib/utils/configParser';
const inputConfig = ref('');
const inputConfigError = ref('');
const config = ref(new WgConfig({
wgInterface: {
listenPort: 51820,
dns: [],
postUp: ['iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE'],
postDown: ['iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE'],
address: ['10.0.0.1/24'],
},
clientsAllowedIps: ['0.0.0.0/0', '::/0'],
}));
watchEffect(() => {
if (inputConfig.value) {
inputConfigError.value = '';
try {
config.value.parse(inputConfig.value);
}
catch (e: any) {
inputConfigError.value = e.toString();
}
}
});
const cidr = computed<string>({
get() {
if (!config.value.wgInterface?.address) {
return '';
}
return config.value.wgInterface.address.join(',') ?? '';
},
set(newValue) {
if (config.value.wgInterface) {
config.value.wgInterface.address = newValue.split(',').map(s => s.trim());
}
},
});
const startIP = ref(2);
const server = computed<string>({
get() {
return config.value.wgInterface?.name ?? '';
},
set(newValue) {
if (config.value.wgInterface) {
config.value.wgInterface.name = newValue;
}
},
});
const serverPort = computed<number>({
get() {
return config.value.wgInterface?.listenPort ?? 51820;
},
set(newValue) {
if (config.value.wgInterface) {
config.value.wgInterface.listenPort = newValue;
}
},
});
const clientAllowedIPs = computed<string>({
get() {
if (!config.value.clientsAllowedIps) {
return '';
}
return config.value.clientsAllowedIps.join(',') ?? '';
},
set(newValue) {
if (config.value) {
config.value.clientsAllowedIps = newValue.split(',').map(s => s.trim());
}
},
});
const endpoint = computed<string>({
get() {
return config.value.endpoint ?? '';
},
set(newValue) {
config.value.endpoint = newValue;
},
});
const dns = computed<string>({
get() {
if (!config.value.wgInterface?.dns) {
return '';
}
return config.value.wgInterface.dns.join(',') ?? '';
},
set(newValue) {
if (config.value.wgInterface) {
config.value.wgInterface.dns = newValue.split(',').map(s => s.trim());
}
},
});
const postUpRule = computed<string>({
get() {
if (!config.value.wgInterface?.postUp) {
return '';
}
return config.value.wgInterface.postUp.join('\n') ?? '';
},
set(newValue) {
if (config.value.wgInterface) {
config.value.wgInterface.postUp = newValue.split('\n').map(s => s.trim());
}
},
});
const postDownRule = computed<string>({
get() {
if (!config.value.wgInterface?.postDown) {
return '';
}
return config.value.wgInterface.postDown.join('\n') ?? '';
},
set(newValue) {
if (config.value.wgInterface) {
config.value.wgInterface.postDown = newValue.split('\n').map(s => s.trim());
}
},
});
const usePreSharedKeys = ref(true);
const numberOfClients = ref(3);
const generatedConfigs = ref<{ server: string; peers: Array<{ name: string; config: string }> } | null>(null);
function generatePeers() {
config.value.clearPeers();
config.value.generateKeys({
preSharedKey: usePreSharedKeys.value,
});
const { start: cidrStartIP } = parseCidr(cidr.value);
for (let i = 0; i < numberOfClients.value; i++) {
const peer = config.value.createPeer({
name: `Client ${i + 1}`,
clientAssignedIP: stringifyIp({
version: 4,
number: BigInt(cidrStartIP) + BigInt(startIP.value) + BigInt(i),
}),
});
config.value.addPeer(peer);
}
generatedConfigs.value = generateConfigString(config.value);
}
</script>
<template>
<div>
<details mb-1>
<summary>Input server configuration</summary>
<c-input-text
v-model:value="inputConfig"
placeholder="Put your input configuration here..."
rows="5"
multiline
mb-2
/>
<c-alert v-if="inputConfigError">
{{ inputConfigError }}
</c-alert>
</details>
<c-card title="Configuration" mb-1>
<n-space>
<c-input-text
v-model:value="server"
label="Server Name:"
placeholder="Server Name or FQDN"
label-position="left"
style="min-width: 400px"
mb-2
/>
<n-form-item label="Server Port:" label-placement="left">
<n-input-number v-model:value="serverPort" min="0" max="65535" />
</n-form-item>
</n-space>
<c-input-text
v-model:value="cidr"
label="Server CIDR:"
placeholder="Server CIDR"
label-position="left"
mb-2
/>
<n-space>
<n-form-item label="Start IP number:" label-placement="left">
<n-input-number v-model:value="startIP" min="2" />
</n-form-item>
<n-form-item label="Number of clients:" label-placement="left">
<n-input-number v-model:value="numberOfClients" min="1" />
</n-form-item>
</n-space>
<n-form-item label="Use Pre Shared Keys" label-placement="left">
<n-checkbox v-model:value="usePreSharedKeys" />
</n-form-item>
<c-input-text
v-model:value="clientAllowedIPs"
label="Client Allowed IPs:"
placeholder="Client Allowed IPs"
label-position="left"
mb-2
/>
<c-input-text
v-model:value="endpoint"
label="Endpoint (optional):"
placeholder="Endpoint"
label-position="left"
mb-2
/>
<c-input-text
v-model:value="dns"
label="DNS"
placeholder="DNS servers:"
label-position="left"
mb-2
/>
<c-input-text
v-model:value="postUpRule"
label="Post-Up rule:"
placeholder="Post-Up rule"
mb-2
/>
<c-input-text
v-model:value="postDownRule"
label="Post-Down rule:"
placeholder="Post-Down rule"
mb-2
/>
</c-card>
<n-space justify="center" mb-2 mt-1>
<n-button @click="generatePeers">
Generate Configurations
</n-button>
</n-space>
<div v-if="generatedConfigs">
<n-card title="Generated Server Config file:">
<textarea-copyable :value="generatedConfigs.server" />
</n-card>
<n-card v-for="(peer, index) in generatedConfigs.peers" :key="index" :label="`${peer.name} - Configuration`">
<n-space>
<textarea-copyable :value="peer.config" />
<QRCodeVue3
:value="peer.config" file-ext="png" :download="true"
:download-options="{ name: peer.name, extension: 'png' }"
/>
</n-space>
</n-card>
</div>
</div>
</template>