@sourceregistry/node-wireguard 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +105 -0
  3. package/bin/x86_64-linux-gnu/node-wireguard.node +0 -0
  4. package/binding.gyp +53 -0
  5. package/lib/binding.d.ts +5 -0
  6. package/lib/binding.js +45 -0
  7. package/lib/index.d.ts +56 -0
  8. package/lib/index.js +115 -0
  9. package/lib/types/AllowedIP.d.ts +5 -0
  10. package/lib/types/AllowedIP.js +2 -0
  11. package/lib/types/Config.d.ts +17 -0
  12. package/lib/types/Config.js +2 -0
  13. package/lib/types/Device.d.ts +23 -0
  14. package/lib/types/Device.js +2 -0
  15. package/lib/types/Key.d.ts +5 -0
  16. package/lib/types/Key.js +2 -0
  17. package/lib/types/Peer.d.ts +22 -0
  18. package/lib/types/Peer.js +2 -0
  19. package/lib/types/PeerConfig.d.ts +24 -0
  20. package/lib/types/PeerConfig.js +2 -0
  21. package/lib/types/index.d.ts +6 -0
  22. package/lib/types/index.js +22 -0
  23. package/package.json +80 -0
  24. package/src/WireGuardClient.cpp +490 -0
  25. package/src/WireGuardClient.h +32 -0
  26. package/src/WireGuardTypes.h +68 -0
  27. package/src/crypto/Key.cpp +77 -0
  28. package/src/crypto/Key.h +30 -0
  29. package/src/helpers/Array.h +26 -0
  30. package/src/helpers/AsyncPromise.h +91 -0
  31. package/src/helpers/IfName.cpp +27 -0
  32. package/src/helpers/IfName.h +17 -0
  33. package/src/netlink/NlAttr.cpp +398 -0
  34. package/src/netlink/NlAttr.h +40 -0
  35. package/src/netlink/NlSocket.cpp +143 -0
  36. package/src/netlink/NlSocket.h +44 -0
  37. package/src/netlink/RtLink.cpp +217 -0
  38. package/src/netlink/RtLink.h +34 -0
  39. package/src/netlink/wireguard_uapi.h +68 -0
  40. package/src/node-wireguard.cpp +48 -0
  41. package/src/uapi/UapiCodec.cpp +185 -0
  42. package/src/uapi/UapiCodec.h +22 -0
  43. package/src/uapi/UapiSocket.cpp +116 -0
  44. package/src/uapi/UapiSocket.h +27 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @sourceregistry/node-wireguard
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@sourceregistry/node-wireguard.svg)](https://www.npmjs.com/package/@sourceregistry/node-wireguard)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@sourceregistry/node-wireguard.svg)](https://www.npmjs.com/package/@sourceregistry/node-wireguard)
5
+ [![CI](https://github.com/SourceRegistry/node-wireguard/actions/workflows/ci.yml/badge.svg)](https://github.com/SourceRegistry/node-wireguard/actions/workflows/ci.yml)
6
+ [![node engine](https://img.shields.io/node/v/@sourceregistry/node-wireguard.svg)](package.json)
7
+ [![license](https://img.shields.io/npm/l/@sourceregistry/node-wireguard.svg)](LICENSE)
8
+
9
+ Native Node.js (N-API) addon for managing WireGuard interfaces and peers on Linux, with a TypeScript API on top. Talks directly to the kernel's `wireguard` generic-netlink family — the same wire protocol [wgctrl-go](https://github.com/WireGuard/wgctrl-go)'s Linux backend uses — plus rtnetlink for interface lifecycle. No shelling out to `wg`/`ip`.
10
+
11
+ Built for [WireGuard®](https://www.wireguard.com/), a registered trademark of Jason A. Donenfeld. This is an independent, unofficial project, not affiliated with or endorsed by the WireGuard project.
12
+
13
+ ## Features
14
+
15
+ - **Full interface lifecycle** — `createDevice()` / `deleteDevice()` (rtnetlink `RTM_NEWLINK`/`RTM_DELLINK`, `IFLA_INFO_KIND=wireguard`). Goes beyond wgctrl-go, which assumes the link already exists.
16
+ - **Address + link state** — `setAddress()` / `deleteAddress()` (rtnetlink `RTM_NEWADDR`/`RTM_DELADDR`) and `setUp()` / `setDown()` (`RTM_NEWLINK` + `IFF_UP`). A freshly created device has no address and is down by default — these are what make it actually pass traffic.
17
+ - **Device + peer configuration** — `configureDevice()` sets private key, listen port, firewall mark, and peers (add/update/remove, allowed-IPs, preshared key, endpoint, persistent keepalive). Mirrors wgtypes' "pointer-optional" semantics: omit a field to leave it unchanged, set it (even to `0`/`''`) to apply/clear it explicitly.
18
+ - **Device + peer inspection** — `devices()` / `device(name)` return live status: peers, handshake times, rx/tx byte counters, allowed-IPs.
19
+ - **Userspace (UAPI) backend fallback** — `devices()`/`device()`/`configureDevice()` automatically use the cross-platform UAPI socket (`/var/run/wireguard/<name>.sock`) for interfaces backed by a userspace implementation like `wireguard-go`, instead of kernel netlink, transparently (`device.type` reports which). Interface lifecycle (`createDevice`/`setUp`/`setAddress`/etc.) is unaffected - those are still plain rtnetlink and work the same either way, since wireguard-go creates a real kernel-visible TUN interface.
20
+ - **Key utilities** — `generatePrivateKey()`, `generatePresharedKey()`, `publicKey()` via libsodium X25519, matching `wg genkey`/`wg genpsk`/`wg pubkey` output (base64, 32 bytes).
21
+ - All blocking netlink syscalls run off the JS thread via `Napi::AsyncWorker` — every `WireGuardClient` method returns a `Promise`.
22
+
23
+ ## Requirements
24
+
25
+ - Linux with the WireGuard kernel module/support loaded (`modprobe wireguard` or built-in).
26
+ - `CAP_NET_ADMIN` (typically: run as root) for `createDevice`/`deleteDevice`/`configureDevice`.
27
+ - Build deps: `libmnl-dev`, `libsodium-dev`, `pkg-config`, a C++17 toolchain.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ npm install
33
+ npm run build
34
+ ```
35
+
36
+ Or use the bundled `.devcontainer` (works on Windows too, via Docker Desktop/WSL2) — see below.
37
+
38
+ ## Usage
39
+
40
+ ```ts
41
+ import { WireGuardClient, generatePrivateKey, publicKey } from '@sourceregistry/node-wireguard';
42
+
43
+ const client = new WireGuardClient();
44
+
45
+ await client.createDevice('wg0');
46
+
47
+ const privateKey = generatePrivateKey();
48
+ await client.configureDevice('wg0', { privateKey, listenPort: 51820 });
49
+
50
+ await client.setAddress('wg0', '10.0.0.1/24');
51
+ await client.setUp('wg0');
52
+
53
+ await client.configureDevice('wg0', {
54
+ peers: [{
55
+ publicKey: '<peer-public-key>',
56
+ endpoint: '203.0.113.5:51820',
57
+ persistentKeepaliveInterval: 25,
58
+ allowedIPs: ['10.0.0.2/32'],
59
+ }],
60
+ });
61
+
62
+ const device = await client.device('wg0');
63
+ console.log(device.publicKey, device.peers);
64
+
65
+ client.close();
66
+ ```
67
+
68
+ More examples in [`examples/`](./examples): `list-devices`, `get-device`, `generate-keypair`, `create-interface`, `add-peer`, `remove-peer`.
69
+
70
+ ## Caveats
71
+
72
+ - Linux only (the UAPI backend means a wireguard-go *peer* anywhere works fine, but this addon itself only runs on Linux).
73
+ - UAPI socket lookup only checks `/var/run/wireguard/<name>.sock` - not `$XDG_RUNTIME_DIR/wireguard/` (which wgctrl-go's wguser backend also checks).
74
+ - Route management (beyond the implicit route rtnetlink installs for an assigned address's own subnet) is left to the caller — use `ip route` or rtnetlink directly for anything beyond that.
75
+ - Calls on one `WireGuardClient` instance are serialized internally (queued, run one at a time in call order) — issuing several without awaiting each is safe but not parallel. Use separate instances if you want calls to actually run concurrently.
76
+
77
+ ## Development
78
+
79
+ ```sh
80
+ npm run build:cpp # node-gyp rebuild
81
+ npm run build:ts # tsc
82
+ npm test # node:test; kernel/UAPI-backed tests auto-skip unless root + the relevant backend is present
83
+ ```
84
+
85
+ A `.devcontainer` is included (Dockerfile + `devcontainer.json`, `capAdd: NET_ADMIN`) so the addon builds and the full test suite — including real interface create/configure/delete — runs the same way on Windows (via Docker Desktop/WSL2) as on Linux.
86
+
87
+ ## Packaging / CI
88
+
89
+ `npm run package` (`scripts/package/package.sh`) builds the addon and stages the compiled `.node` into `bin/<arch-triplet>/` (currently `x86_64-linux-gnu`, `aarch64-linux-gnu`), where `lib/binding.ts` looks for a prebuild when installed from npm. If no matching prebuild is present (e.g. an unpublished triplet), `npm install`'s `gypfile`-triggered `node-gyp rebuild` compiles it locally instead, and the loader falls back to that build automatically.
90
+
91
+ `.github/workflows/ci.yml` runs on push/PR: installs native deps (`libmnl-dev`/`libsodium-dev`), builds, typechecks, and runs the test suite as root with `modprobe wireguard` best-effort (kernel-backed tests self-skip if the module isn't available on the runner) - plus a separate job that stages a prebuild and runs `npm pack --dry-run` to catch packaging regressions.
92
+
93
+ ## Releasing
94
+
95
+ Releases are automated with [semantic-release](https://semantic-release.gitbook.io/) off [Conventional Commits](https://www.conventionalcommits.org/) (`fix:`, `feat:`, `feat!:`/`BREAKING CHANGE:`, etc.) - on every push to `main` (stable) or `alpha` (prerelease) that passes CI, the `release` job:
96
+
97
+ 1. Determines the next version from commit messages since the last release.
98
+ 2. Builds the addon and runs `prepublishOnly` (`npm run package`) to stage the `bin/<triplet>/` prebuild into the tarball.
99
+ 3. Publishes to npm and pushes a GitHub release + tag + `CHANGELOG.md` update.
100
+
101
+ Requires repo secrets `NPM_TOKEN` (npm publish) and the default `GITHUB_TOKEN` (release/tag/changelog commit). Only the runner's own architecture (`x86_64-linux-gnu` on GitHub-hosted `ubuntu-latest`) gets a prebuild this way - other architectures fall back to compiling from source on `npm install` (see Packaging above).
102
+
103
+ ## License
104
+
105
+ Apache-2.0
package/binding.gyp ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "targets": [
3
+ {
4
+ "target_name": "node-wireguard",
5
+ "sources": [
6
+ "src/node-wireguard.cpp",
7
+ "src/WireGuardClient.cpp",
8
+ "src/netlink/NlSocket.cpp",
9
+ "src/netlink/NlAttr.cpp",
10
+ "src/netlink/RtLink.cpp",
11
+ "src/helpers/IfName.cpp",
12
+ "src/crypto/Key.cpp",
13
+ "src/uapi/UapiSocket.cpp",
14
+ "src/uapi/UapiCodec.cpp"
15
+ ],
16
+ "include_dirs": [
17
+ "<!@(node -p \"require('node-addon-api').include\")",
18
+ "<!@(pkg-config --cflags-only-I libmnl libsodium | sed 's/-I//g')"
19
+ ],
20
+ "dependencies": [
21
+ "<!(node -p \"require('node-addon-api').gyp\")"
22
+ ],
23
+ "cflags!": ["-fno-exceptions"],
24
+ "cflags_cc!": ["-fno-exceptions"],
25
+ "cflags_cc": ["-std=c++17"],
26
+ "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"],
27
+ "conditions": [
28
+ [
29
+ "OS=='linux'",
30
+ {
31
+ "libraries": [
32
+ "<!@(pkg-config --libs libmnl libsodium)"
33
+ ]
34
+ }
35
+ ],
36
+ [
37
+ "OS!='linux'",
38
+ {
39
+ "type": "none"
40
+ }
41
+ ]
42
+ ],
43
+ "xcode_settings": {
44
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
45
+ "CLANG_CXX_LIBRARY": "libc++",
46
+ "MACOSX_DEPLOYMENT_TARGET": "10.7"
47
+ },
48
+ "msvs_settings": {
49
+ "VCCLCompilerTool": {"ExceptionHandling": 1}
50
+ }
51
+ }
52
+ ]
53
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @author A.P.A. Slaa (a.p.a.slaa@projectsource.nl) ProjectSource V.O.F.
3
+ */
4
+ declare const _default: any;
5
+ export default _default;
package/lib/binding.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ /**
3
+ * @author A.P.A. Slaa (a.p.a.slaa@projectsource.nl) ProjectSource V.O.F.
4
+ */
5
+ var __importDefault = (this && this.__importDefault) || function (mod) {
6
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const platform = process.platform;
12
+ const arch = process.arch;
13
+ const base_name = "node-wireguard";
14
+ const is_package = __dirname.includes("node_modules");
15
+ function devAddonPath() {
16
+ const mode = process.env["NODE_ENV"] === "development" ? "Debug" : "Release";
17
+ if (mode === "Debug") {
18
+ console.warn("!!!RUNNING IN DEVELOPMENT MODE!!!");
19
+ }
20
+ return path_1.default.join(__dirname, '..', 'build', mode, `${base_name}.node`);
21
+ }
22
+ function packagedAddonPath() {
23
+ const archToTriplet = {
24
+ x64: 'x86_64-linux-gnu',
25
+ arm64: 'aarch64-linux-gnu',
26
+ };
27
+ const triplet = platform === 'linux' ? archToTriplet[arch] : undefined;
28
+ return triplet ? path_1.default.join(__dirname, '..', 'bin', triplet, `${base_name}.node`) : undefined;
29
+ }
30
+ let addonPath;
31
+ if (is_package) {
32
+ // Prefer a shipped prebuild (bin/<triplet>/); fall back to whatever
33
+ // `npm install`'s gypfile-triggered node-gyp rebuild produced locally
34
+ // (build/Release/) when no matching prebuild was published.
35
+ const packaged = packagedAddonPath();
36
+ addonPath = packaged && fs_1.default.existsSync(packaged) ? packaged : devAddonPath();
37
+ }
38
+ else {
39
+ addonPath = devAddonPath();
40
+ }
41
+ if (!addonPath || !fs_1.default.existsSync(addonPath)) {
42
+ throw new Error(`node-wireguard: no native addon found at ${addonPath} (platform=${platform}, arch=${arch}). ` +
43
+ `Run \`npm run build\` (development) or \`npm run package\` (to stage a prebuild) first.`);
44
+ }
45
+ exports.default = require(addonPath);
package/lib/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @author A.P.A. Slaa (a.p.a.slaa@projectsource.nl) ProjectSource V.O.F.
3
+ */
4
+ import { Device } from './types/Device';
5
+ import { Config } from './types/Config';
6
+ export * from './types';
7
+ /**
8
+ * Manages WireGuard interfaces and their peers via the kernel's "wireguard"
9
+ * generic-netlink family - the same protocol wgctrl-go's Linux backend uses -
10
+ * plus rtnetlink-based interface lifecycle (createDevice/deleteDevice), which
11
+ * wgctrl-go itself does not provide.
12
+ *
13
+ * Linux only. Requires CAP_NET_ADMIN (typically: run as root).
14
+ *
15
+ * Calls on one instance are serialized (queued internally) since the
16
+ * underlying netlink socket is not safe for overlapping use - issuing two
17
+ * calls without awaiting the first no longer corrupts the socket, but they
18
+ * still execute one at a time, in call order. Use separate WireGuardClient
19
+ * instances if you actually want concurrent (parallel) netlink calls.
20
+ */
21
+ export declare class WireGuardClient {
22
+ private native;
23
+ private queue;
24
+ constructor();
25
+ private enqueue;
26
+ /** Creates a new WireGuard-type network interface. Rejects with code 'EEXIST' if it already exists. */
27
+ createDevice(name: string): Promise<void>;
28
+ /** Deletes a WireGuard interface. Rejects with code 'ENODEV' if it doesn't exist. */
29
+ deleteDevice(name: string): Promise<void>;
30
+ /** Lists every WireGuard interface currently present on the system. */
31
+ devices(): Promise<Device[]>;
32
+ /** Fetches one WireGuard interface by name. Rejects with code 'ENODEV' if it's not a WireGuard interface. */
33
+ device(name: string): Promise<Device>;
34
+ /** Applies a configuration to an existing WireGuard interface. See {@link Config} for field semantics. */
35
+ configureDevice(name: string, cfg: Config): Promise<void>;
36
+ /** Brings the interface administratively up. Required for traffic to flow - createDevice() leaves it down. */
37
+ setUp(name: string): Promise<void>;
38
+ /** Brings the interface administratively down. */
39
+ setDown(name: string): Promise<void>;
40
+ /** Assigns a local address (e.g. "10.0.0.1/24") to the interface. Replaces any existing address with the same prefix. */
41
+ setAddress(name: string, cidr: string): Promise<void>;
42
+ /** Removes a previously assigned address. */
43
+ deleteAddress(name: string, cidr: string): Promise<void>;
44
+ /**
45
+ * Releases the underlying netlink socket. The instance is unusable
46
+ * afterwards. Does not wait for queued calls to finish - close() after
47
+ * awaiting your last call, not concurrently with it.
48
+ */
49
+ close(): void;
50
+ }
51
+ /** Generates a new Curve25519 private key, base64-encoded (same form as `wg genkey`). */
52
+ export declare function generatePrivateKey(): string;
53
+ /** Generates a new opaque preshared key, base64-encoded (same form as `wg genpsk`). */
54
+ export declare function generatePresharedKey(): string;
55
+ /** Derives the base64-encoded public key for a base64-encoded private key (same as `wg pubkey`). */
56
+ export declare function publicKey(privateKey: string): string;
package/lib/index.js ADDED
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ /**
3
+ * @author A.P.A. Slaa (a.p.a.slaa@projectsource.nl) ProjectSource V.O.F.
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ var __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.WireGuardClient = void 0;
24
+ exports.generatePrivateKey = generatePrivateKey;
25
+ exports.generatePresharedKey = generatePresharedKey;
26
+ exports.publicKey = publicKey;
27
+ const binding_1 = __importDefault(require("./binding"));
28
+ __exportStar(require("./types"), exports);
29
+ const native = binding_1.default;
30
+ /**
31
+ * Manages WireGuard interfaces and their peers via the kernel's "wireguard"
32
+ * generic-netlink family - the same protocol wgctrl-go's Linux backend uses -
33
+ * plus rtnetlink-based interface lifecycle (createDevice/deleteDevice), which
34
+ * wgctrl-go itself does not provide.
35
+ *
36
+ * Linux only. Requires CAP_NET_ADMIN (typically: run as root).
37
+ *
38
+ * Calls on one instance are serialized (queued internally) since the
39
+ * underlying netlink socket is not safe for overlapping use - issuing two
40
+ * calls without awaiting the first no longer corrupts the socket, but they
41
+ * still execute one at a time, in call order. Use separate WireGuardClient
42
+ * instances if you actually want concurrent (parallel) netlink calls.
43
+ */
44
+ class WireGuardClient {
45
+ constructor() {
46
+ this.queue = Promise.resolve();
47
+ this.native = new native.WireGuardClient();
48
+ }
49
+ // Chains `task` after every previously enqueued task, so only one native
50
+ // call is ever in flight at a time. A rejected task must not break the
51
+ // chain for tasks queued after it - only the caller of that task should
52
+ // see the rejection.
53
+ enqueue(task) {
54
+ const result = this.queue.then(task, task);
55
+ this.queue = result.then(() => undefined, () => undefined);
56
+ return result;
57
+ }
58
+ /** Creates a new WireGuard-type network interface. Rejects with code 'EEXIST' if it already exists. */
59
+ createDevice(name) {
60
+ return this.enqueue(() => this.native.createDevice(name));
61
+ }
62
+ /** Deletes a WireGuard interface. Rejects with code 'ENODEV' if it doesn't exist. */
63
+ deleteDevice(name) {
64
+ return this.enqueue(() => this.native.deleteDevice(name));
65
+ }
66
+ /** Lists every WireGuard interface currently present on the system. */
67
+ devices() {
68
+ return this.enqueue(() => this.native.devices());
69
+ }
70
+ /** Fetches one WireGuard interface by name. Rejects with code 'ENODEV' if it's not a WireGuard interface. */
71
+ device(name) {
72
+ return this.enqueue(() => this.native.device(name));
73
+ }
74
+ /** Applies a configuration to an existing WireGuard interface. See {@link Config} for field semantics. */
75
+ configureDevice(name, cfg) {
76
+ return this.enqueue(() => this.native.configureDevice(name, cfg));
77
+ }
78
+ /** Brings the interface administratively up. Required for traffic to flow - createDevice() leaves it down. */
79
+ setUp(name) {
80
+ return this.enqueue(() => this.native.setUp(name));
81
+ }
82
+ /** Brings the interface administratively down. */
83
+ setDown(name) {
84
+ return this.enqueue(() => this.native.setDown(name));
85
+ }
86
+ /** Assigns a local address (e.g. "10.0.0.1/24") to the interface. Replaces any existing address with the same prefix. */
87
+ setAddress(name, cidr) {
88
+ return this.enqueue(() => this.native.setAddress(name, cidr));
89
+ }
90
+ /** Removes a previously assigned address. */
91
+ deleteAddress(name, cidr) {
92
+ return this.enqueue(() => this.native.deleteAddress(name, cidr));
93
+ }
94
+ /**
95
+ * Releases the underlying netlink socket. The instance is unusable
96
+ * afterwards. Does not wait for queued calls to finish - close() after
97
+ * awaiting your last call, not concurrently with it.
98
+ */
99
+ close() {
100
+ this.native.close();
101
+ }
102
+ }
103
+ exports.WireGuardClient = WireGuardClient;
104
+ /** Generates a new Curve25519 private key, base64-encoded (same form as `wg genkey`). */
105
+ function generatePrivateKey() {
106
+ return native.generatePrivateKey();
107
+ }
108
+ /** Generates a new opaque preshared key, base64-encoded (same form as `wg genpsk`). */
109
+ function generatePresharedKey() {
110
+ return native.generatePresharedKey();
111
+ }
112
+ /** Derives the base64-encoded public key for a base64-encoded private key (same as `wg pubkey`). */
113
+ function publicKey(privateKey) {
114
+ return native.publicKey(privateKey);
115
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * An allowed IP range in CIDR notation, e.g. "10.0.0.2/32" or "fd00::/64".
3
+ * 0.0.0.0/0 / ::/0 allow all IPv4 / IPv6 traffic, matching wgtypes.AllowedIPs.
4
+ */
5
+ export type AllowedIP = string;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
1
+ import { Key } from './Key';
2
+ import { PeerConfig } from './PeerConfig';
3
+ /**
4
+ * Device configuration input for WireGuardClient.configureDevice() (mirrors
5
+ * wgtypes.Config). Optional fields follow wgctrl-go's pointer semantics:
6
+ * `undefined` = leave unchanged, a present value (including 0 / '') = apply it.
7
+ */
8
+ export interface Config {
9
+ /** undefined = unchanged; '' (all-zero key) clears the private key. */
10
+ privateKey?: Key;
11
+ listenPort?: number;
12
+ /** undefined = unchanged; 0 clears the firewall mark. */
13
+ firewallMark?: number;
14
+ /** Replace the device's entire peer list instead of merging into it. */
15
+ replacePeers?: boolean;
16
+ peers?: PeerConfig[];
17
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,23 @@
1
+ import { Key } from './Key';
2
+ import { Peer } from './Peer';
3
+ /**
4
+ * Backend that produced this Device: 'linux-kernel' for the kernel module
5
+ * (genetlink), 'userspace' for a UAPI-socket-backed implementation like
6
+ * wireguard-go (e.g. /var/run/wireguard/<name>.sock).
7
+ */
8
+ export type DeviceType = 'linux-kernel' | 'userspace';
9
+ /**
10
+ * Read-only snapshot of a WireGuard interface, as returned by
11
+ * WireGuardClient.device()/devices() (mirrors wgtypes.Device).
12
+ */
13
+ export interface Device {
14
+ name: string;
15
+ type: DeviceType;
16
+ /** Empty string if no private key is set. */
17
+ privateKey: Key;
18
+ /** Empty string if no private key is set (no public key can be derived). */
19
+ publicKey: Key;
20
+ listenPort: number;
21
+ firewallMark: number;
22
+ peers: Peer[];
23
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A WireGuard key (private, public, or preshared) as a base64-encoded
3
+ * 32-byte Curve25519 value - the same string form `wg` and wgctrl-go use.
4
+ */
5
+ export type Key = string;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });