Skip to content

Commit

Permalink
Droping rebory and migrate to cmake-js (#14)
Browse files Browse the repository at this point in the history
- Migrate to cmake-js
- Fix and pretty userspace in go binding
- fix typescript code
Reviewed-on: https://sirherobrine23.org/Wireguard/Wireguard-tools.js/pulls/14
Co-authored-by: Matheus Sampaio Queiroga <[email protected]>
Co-committed-by: Matheus Sampaio Queiroga <[email protected]>
  • Loading branch information
Sirherobrine23 authored and Gitea committed Jul 9, 2024
1 parent b26f59e commit 5282a0c
Show file tree
Hide file tree
Showing 26 changed files with 565 additions and 847 deletions.
13 changes: 4 additions & 9 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [ 16.x, 18.x, 20.x, latest ]
node-version: [ 18.x, 20.x, 21.x, latest ]
steps:
- name: Disable sudo PATH replace
run: |
Expand All @@ -32,18 +32,13 @@ jobs:
- uses: actions/setup-go@v4
with:
go-version-file: addon/userspace/go/go.mod
go-version: ">=1.22.0"

- name: "Setup zig"
uses: korandoru/setup-zig@v1
with:
zig-version: "master"
go-version: ">=1.22"

- name: Install build dependencies
run: sudo apt update && sudo apt install -y build-essential
run: sudo apt update && sudo apt install -y build-essential cmake

- name: Install node dependencies
run: npm install --no-save --no-audit --no-fund --ignore-scripts

- name: Run tests
run: ./node_modules/.bin/rebory build && sudo node --no-warnings --loader ts-node/esm src/index_test.js
run: npm run build && sudo node --no-warnings --loader ts-node/esm src/index_test.js
10 changes: 7 additions & 3 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@
node_modules/
/*.tgz

# Builder dir
build/

# Typescript
src/**/*_test.*
src/**/*.ts
!src/**/*.d.ts

# vscode
# IDEs
.devcontainer/
.vscode/
.vscode-ctags
.vscode/
.zed/

# Github and Git
.github/
.git*

# Project
.vscode-ctags*
*.addrs.json
*.addrs.json
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@
"xtr1common": "cpp",
"xtree": "cpp",
"xutility": "cpp",
"fstream": "cpp"
"fstream": "cpp",
"deque": "cpp",
"stack": "cpp"
}
}
38 changes: 38 additions & 0 deletions .zed/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Folder-specific settings
//
// For a full list of overridable settings, and general information on folder-specific settings,
// see the documentation: https://zed.dev/docs/configuring-zed#folder-specific-settings
{
"remove_trailing_whitespace_on_save": true,
"ensure_final_newline_on_save": true,
"formatter": "auto",
"format_on_save": "off",
"tab_size": 2,
"languages": {
"TypeScript": {
"hard_tabs": false
"format_on_save": true,
"code_actions_on_format": {
"source.organizeImports": true,
"source.removeUnusedImports": true
}
},
"JavaScript": {
"hard_tabs": false
"format_on_save": true,
"code_actions_on_format": {
"source.organizeImports": true,
"source.removeUnusedImports": true
}
},
"Go": {
"format_on_save": true
},
"C++": {
"hard_tabs": false
},
"C": {
"hard_tabs": false
}
}
}
98 changes: 98 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
cmake_minimum_required(VERSION 3.15)
cmake_policy(SET CMP0091 NEW)
cmake_policy(SET CMP0042 NEW)

project (wg)

add_compile_definitions(NAPI_VERSION=8 NAPI_CPP_EXCEPTIONS)
# set_target_properties(PROPERTIES CXX_STANDARD 17)
# set_target_properties(PROPERTIES C_STANDARD 17)
set(CMAKE_C_STANDARD 17)
set(CMAKE_CXX_STANDARD 17)

include_directories(${CMAKE_JS_INC})
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/addon")
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/addon/genKey")
# Include N-API wrappers
# $ node -p "require('node-addon-api').include"
# "/home/will/projects/financialcpp/financialcpp/node_modules/node-addon-api"
execute_process(COMMAND node -p "require('node-addon-api').include"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE NODE_ADDON_API_DIR
)

# strip `"` and `\n` from the output above
string(REPLACE "\n" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
string(REPLACE "\"" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})

include_directories(PRIVATE ${NODE_ADDON_API_DIR})

if(UNIX)
add_definitions(-fpermissive -fexceptions -w -fpermissive -fPIC)
endif()

file(GLOB GSOURCE_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/addon/main.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/addon/genKey/wgkeys.cpp"
)

if(MSVC)
file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/addon/win/wginterface.cpp")
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/addon/win")
add_compile_definitions(_HAS_EXCEPTIONS=1 ONSTARTADDON)
target_link_libraries(${PROJECT_NAME}
"wbemuuid.lib"
"bcrypt.lib"
"crypt32.lib"
"iphlpapi.lib"
"kernel32.lib"
"ntdll.lib"
"ws2_32.lib"
"setupapi.lib"
)
elseif(UNIX AND NOT APPLE OR ANDROID)
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/addon/linux")
file(GLOB SOURCE_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/addon/linux/wireguard.c"
"${CMAKE_CURRENT_SOURCE_DIR}/addon/linux/wginterface.cpp"
)
else()
message(STATUS "Buiding go Userspace")
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/wg-go.o)
file(REMOVE_RECURSE ${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/wg-go.o)
endif()
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/wg-go.h)
file(REMOVE_RECURSE ${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/wg-go.h)
endif()
set(ENV{CGO_ENABLED} 1)
set(ENV{LDFLAGS} -w)
# Remove CXX and CC envs to CGO
set(ENV{DCXX} ENV{CXX})
set(ENV{DCC} ENV{CC})
set(ENV{CXX})
set(ENV{CC})
execute_process(
COMMAND go build -trimpath -v -o ../wg-go.o -buildmode c-archive .
# COMMAND env
RESULT_VARIABLE GOCODE
OUTPUT_VARIABLE GOBUILDLOG
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/go
)
set(ENV{CXX} ENV{DCXX})
set(ENV{CC} ENV{DCC})
if(NOT GOCODE EQUAL "0")
message(FATAL_ERROR "cannot build go userspace code exit ${GOCODE}\n${GOBUILDLOG}")
endif()
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace")
set(USERSPACEOBJ ${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/wg-go.o)
file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/addon/userspace/wginterface.cpp")
endif()

add_library(${PROJECT_NAME} SHARED ${GSOURCE_FILES} ${SOURCE_FILES} ${CMAKE_JS_SRC})
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
target_link_libraries(${PROJECT_NAME} ${USERSPACEOBJ} ${CMAKE_JS_LIB})

if(MSVC AND CMAKE_JS_NODELIB_DEF AND CMAKE_JS_NODELIB_TARGET)
# Generate node.lib
execute_process(COMMAND ${CMAKE_AR} /def:${CMAKE_JS_NODELIB_DEF} /out:${CMAKE_JS_NODELIB_TARGET} ${CMAKE_STATIC_LINKER_FLAGS})
endif()
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,42 @@

Manage your Wireguard interfaces directly from Node.js without any wrappers over `wg` or `wg-quick`

> [!WARNING]
> Require cmake and tools (GCC/GCC++, clang or Visual Studio) to build this addon
>
> New versions does't include prebuilt binaries
```js
import { setConfig, getConfig, key, Config } from "../index.js"

const tunName = process.platform === "darwin" ? "utun10" : "wg3" // Tunnel name, in MacOS/Darwin require start with utun prefix
let currentConfig: Config
try {
currentConfig = await getConfig(tunName) // Check if exists tun
} catch {
// Create new wireguard tun
currentConfig = {
name: tunName,
privateKey: await key.privateKey(),
portListen: 5820,
address: [
"10.66.66.1/24"
],
peers: {}
}
}

// Add new Peer
const peerPrivate = await key.privateKey()
currentConfig.peers[key.publicKey(peerPrivate)] = {
presharedKey: await key.presharedKey(),
allowedIPs: [
"10.66.66.2/24"
]
}

// Deploy new Config
await setConfig(currentConfig)
```

## Licences
Expand Down
18 changes: 11 additions & 7 deletions addon/genKey/wgkeys.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#include "wgkeys.hh"
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <random>
#include <sstream>
#include <string.h>

#ifdef __linux__
Expand Down Expand Up @@ -263,7 +265,7 @@ void wgKeys::generatePublic(wg_key public_key, const wg_key private_key) {
memzero_explicit(f, sizeof(f));
}

std::string wgKeys::generatePublic(const std::string private_key) {
std::string wgKeys::generatePublic(const std::string &private_key) {
wg_key public_key;
wg_key private_key_;
stringToKey(private_key_, private_key);
Expand All @@ -282,7 +284,7 @@ bool key_is_zero(const uint8_t key[32]) {
}

void wgKeys::stringToKey(wg_key key, std::string keyBase64) {
auto base64 = keyBase64.c_str();
const char* base64 = keyBase64.c_str();
if (keyBase64.length() != B64_WG_KEY_LENGTH ||
base64[B64_WG_KEY_LENGTH - 1] != '=')
throw std::string("invalid key, length: ")
Expand Down Expand Up @@ -315,8 +317,7 @@ std::string wgKeys::toString(const wg_key key) {
wg_key_b64_string base64;
unsigned int i;

for (i = 0; i < 32 / 3; ++i)
encode_base64(&base64[i * 4], &key[i * 3]);
for (i = 0; i < 32 / 3; ++i) encode_base64(&base64[i * 4], &key[i * 3]);
const uint8_t tempKey[3] = {key[i * 3 + 0], key[i * 3 + 1], 0};
encode_base64(&base64[i * 4], tempKey);
base64[sizeof(wg_key_b64_string) - 2] = '=';
Expand All @@ -325,7 +326,7 @@ std::string wgKeys::toString(const wg_key key) {
return std::string(base64);
}

std::string wgKeys::toHex(const std::string keyBase64) {
std::string wgKeys::toHex(const std::string &keyBase64) {
wg_key key;
wgKeys::stringToKey(key, keyBase64);
char hex[65];
Expand All @@ -334,8 +335,11 @@ std::string wgKeys::toHex(const std::string keyBase64) {
return std::string(hex);
}

std::string wgKeys::HextoBase64(const std::string keyHex) {
std::string wgKeys::HextoBase64(const std::string &s_hex) {
wg_key key;
for (int i = 0; i < 32; ++i) sscanf(keyHex.c_str() + i * 2, "%02x", &key[i]);
for(unsigned i = 0, uchr ; i < s_hex.length() ; i += 2) {
sscanf( s_hex.c_str()+ i, "%2x", &uchr); // conversion
key[i/2] = uchr; // save as char
}
return wgKeys::toString(key);
}
6 changes: 3 additions & 3 deletions addon/genKey/wgkeys.hh
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ namespace wgKeys {
std::string toString(const wg_key key);

// Convert base64 to hex key
std::string toHex(const std::string keyBase64);
std::string toHex(const std::string &keyBase64);

// Convert hex to base64
std::string HextoBase64(const std::string keyHex);
std::string HextoBase64(const std::string &keyHex);

// Convert base64 to wg_key
void stringToKey(wg_key key, std::string keyBase64);
Expand All @@ -31,7 +31,7 @@ namespace wgKeys {
// Get public key from private key
void generatePublic(wg_key public_key, const wg_key private_key);

std::string generatePublic(const std::string private_key);
std::string generatePublic(const std::string &private_key);
}

#endif
4 changes: 2 additions & 2 deletions addon/linux/wginterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ std::string getWireguardVersion() {
#endif

std::string version = "Unknown";

// /sys/module/wireguard/version - for kernel module
if (std::filesystem::exists("/sys/module/wireguard/version")) {
std::ifstream file("/sys/module/wireguard/version");
Expand Down Expand Up @@ -100,9 +100,9 @@ void WireguardConfig::getWireguardConfig() {
for ((peer) = (devConfig)->first_peer; (peer); (peer) = (peer)->next_peer) {
auto PeerConfig = Peer();
if (peer->flags & WGPEER_HAS_PRESHARED_KEY) PeerConfig.presharedKey = wgKeys::toString(peer->preshared_key);
if (peer->flags & WGPEER_HAS_PERSISTENT_KEEPALIVE_INTERVAL) PeerConfig.keepInterval = peer->persistent_keepalive_interval;
if (peer->endpoint.addr.sa_family == AF_INET||peer->endpoint.addr.sa_family == AF_INET6) PeerConfig.endpoint = HostAdresses(true, &peer->endpoint.addr);

PeerConfig.keepInterval = peer->persistent_keepalive_interval;
PeerConfig.lastHandshake = peer->last_handshake_time.tv_sec*1000;
PeerConfig.rxBytes = peer->rx_bytes;
PeerConfig.txBytes = peer->tx_bytes;
Expand Down
12 changes: 0 additions & 12 deletions addon/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,6 @@ Napi::Object StartAddon(const Napi::Env env, const Napi::Object exports) {
}
}));

exports.Set("listDevices", Napi::Function::New(env, [](const Napi::CallbackInfo &info) -> Napi::Value {
const Napi::Env env = info.Env();
try {
ListDevices *worker = new ListDevices(env);
worker->Queue();
return worker->NodePromise.Promise();
} catch (std::string &err) {
Napi::Error::New(env, err).ThrowAsJavaScriptException();
return env.Undefined();
}
}));

exports.Set("setConfig", Napi::Function::New(env, [](const Napi::CallbackInfo &info) -> Napi::Value {
const Napi::Env env = info.Env();
if (!(info[0].IsObject())) Napi::Error::New(env, "Set wireguard config!").ThrowAsJavaScriptException();
Expand Down
6 changes: 0 additions & 6 deletions addon/userspace/go/go.sum
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4=
github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44=
Expand Down
Loading

0 comments on commit 5282a0c

Please sign in to comment.