opendht 0.0.0-stage → 4.4.100

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 (122) hide show
  1. package/README.md +254 -2
  2. package/crypto.js +56 -0
  3. package/examples/dhtnode.js +176 -0
  4. package/examples/dhtnode.ts +171 -0
  5. package/index.d.ts +104 -0
  6. package/index.js +87 -0
  7. package/package.json +57 -5
  8. package/prebuilds/darwin-arm64/libargon2.1.dylib +0 -0
  9. package/prebuilds/darwin-arm64/libfmt.12.2.0.dylib +0 -0
  10. package/prebuilds/darwin-arm64/libgmp.10.dylib +0 -0
  11. package/prebuilds/darwin-arm64/libgnutls.30.dylib +0 -0
  12. package/prebuilds/darwin-arm64/libhogweed.7.0.dylib +0 -0
  13. package/prebuilds/darwin-arm64/libidn2.0.dylib +0 -0
  14. package/prebuilds/darwin-arm64/libintl.8.dylib +0 -0
  15. package/prebuilds/darwin-arm64/libjsoncpp.27.dylib +0 -0
  16. package/prebuilds/darwin-arm64/libnettle.9.0.dylib +0 -0
  17. package/prebuilds/darwin-arm64/libopendht.4.4.99.dylib +0 -0
  18. package/prebuilds/darwin-arm64/libp11-kit.0.dylib +0 -0
  19. package/prebuilds/darwin-arm64/libsimdutf.35.0.0.dylib +0 -0
  20. package/prebuilds/darwin-arm64/libtasn1.6.dylib +0 -0
  21. package/prebuilds/darwin-arm64/libunistring.5.dylib +0 -0
  22. package/prebuilds/darwin-arm64/licenses/OpenDHT-LICENSE.txt +7 -0
  23. package/prebuilds/darwin-arm64/licenses/argon2-LICENSE.txt +314 -0
  24. package/prebuilds/darwin-arm64/licenses/fmt-LICENSE.txt +20 -0
  25. package/prebuilds/darwin-arm64/licenses/gettext-COPYING.txt +674 -0
  26. package/prebuilds/darwin-arm64/licenses/gmp-COPYING.LESSERv3.txt +165 -0
  27. package/prebuilds/darwin-arm64/licenses/gmp-COPYING.txt +674 -0
  28. package/prebuilds/darwin-arm64/licenses/gnutls-COPYING.LESSERv2.txt +501 -0
  29. package/prebuilds/darwin-arm64/licenses/gnutls-COPYING.txt +674 -0
  30. package/prebuilds/darwin-arm64/licenses/jsoncpp-LICENSE.txt +55 -0
  31. package/prebuilds/darwin-arm64/licenses/libidn2-COPYING.LESSERv3.txt +165 -0
  32. package/prebuilds/darwin-arm64/licenses/libidn2-COPYING.txt +674 -0
  33. package/prebuilds/darwin-arm64/licenses/libidn2-COPYING.unicode.txt +91 -0
  34. package/prebuilds/darwin-arm64/licenses/libtasn1-COPYING.LESSERv2.txt +501 -0
  35. package/prebuilds/darwin-arm64/licenses/libtasn1-COPYING.txt +674 -0
  36. package/prebuilds/darwin-arm64/licenses/libunistring-COPYING.LIB.txt +165 -0
  37. package/prebuilds/darwin-arm64/licenses/libunistring-COPYING.txt +674 -0
  38. package/prebuilds/darwin-arm64/licenses/nettle-COPYING.LESSERv3.txt +165 -0
  39. package/prebuilds/darwin-arm64/licenses/p11-kit-COPYING.txt +27 -0
  40. package/prebuilds/darwin-arm64/licenses/simdutf-LICENSE-APACHE.txt +201 -0
  41. package/prebuilds/darwin-arm64/licenses/simdutf-LICENSE-MIT.txt +18 -0
  42. package/prebuilds/darwin-arm64/manifest.json +22 -0
  43. package/prebuilds/darwin-arm64/node.napi.node +0 -0
  44. package/prebuilds/darwin-x64/libargon2.1.dylib +0 -0
  45. package/prebuilds/darwin-x64/libfmt.12.2.0.dylib +0 -0
  46. package/prebuilds/darwin-x64/libgmp.10.dylib +0 -0
  47. package/prebuilds/darwin-x64/libgnutls.30.dylib +0 -0
  48. package/prebuilds/darwin-x64/libhogweed.7.0.dylib +0 -0
  49. package/prebuilds/darwin-x64/libidn2.0.dylib +0 -0
  50. package/prebuilds/darwin-x64/libintl.8.dylib +0 -0
  51. package/prebuilds/darwin-x64/libjsoncpp.27.dylib +0 -0
  52. package/prebuilds/darwin-x64/libnettle.9.0.dylib +0 -0
  53. package/prebuilds/darwin-x64/libopendht.4.4.99.dylib +0 -0
  54. package/prebuilds/darwin-x64/libp11-kit.0.dylib +0 -0
  55. package/prebuilds/darwin-x64/libsimdutf.35.0.0.dylib +0 -0
  56. package/prebuilds/darwin-x64/libtasn1.6.dylib +0 -0
  57. package/prebuilds/darwin-x64/libunistring.5.dylib +0 -0
  58. package/prebuilds/darwin-x64/licenses/OpenDHT-LICENSE.txt +7 -0
  59. package/prebuilds/darwin-x64/licenses/argon2-LICENSE.txt +314 -0
  60. package/prebuilds/darwin-x64/licenses/fmt-LICENSE.txt +20 -0
  61. package/prebuilds/darwin-x64/licenses/gettext-COPYING.txt +674 -0
  62. package/prebuilds/darwin-x64/licenses/gmp-COPYING.LESSERv3.txt +165 -0
  63. package/prebuilds/darwin-x64/licenses/gmp-COPYING.txt +674 -0
  64. package/prebuilds/darwin-x64/licenses/gnutls-COPYING.LESSERv2.txt +501 -0
  65. package/prebuilds/darwin-x64/licenses/gnutls-COPYING.txt +674 -0
  66. package/prebuilds/darwin-x64/licenses/jsoncpp-LICENSE.txt +55 -0
  67. package/prebuilds/darwin-x64/licenses/libidn2-COPYING.LESSERv3.txt +165 -0
  68. package/prebuilds/darwin-x64/licenses/libidn2-COPYING.txt +674 -0
  69. package/prebuilds/darwin-x64/licenses/libidn2-COPYING.unicode.txt +91 -0
  70. package/prebuilds/darwin-x64/licenses/libtasn1-COPYING.LESSERv2.txt +501 -0
  71. package/prebuilds/darwin-x64/licenses/libtasn1-COPYING.txt +674 -0
  72. package/prebuilds/darwin-x64/licenses/libunistring-COPYING.LIB.txt +165 -0
  73. package/prebuilds/darwin-x64/licenses/libunistring-COPYING.txt +674 -0
  74. package/prebuilds/darwin-x64/licenses/nettle-COPYING.LESSERv3.txt +165 -0
  75. package/prebuilds/darwin-x64/licenses/p11-kit-COPYING.txt +27 -0
  76. package/prebuilds/darwin-x64/licenses/simdutf-LICENSE-APACHE.txt +201 -0
  77. package/prebuilds/darwin-x64/licenses/simdutf-LICENSE-MIT.txt +18 -0
  78. package/prebuilds/darwin-x64/manifest.json +22 -0
  79. package/prebuilds/darwin-x64/node.napi.node +0 -0
  80. package/prebuilds/linux-x64/libargon2.so.1 +0 -0
  81. package/prebuilds/linux-x64/libffi.so.8 +0 -0
  82. package/prebuilds/linux-x64/libfmt.so.9 +0 -0
  83. package/prebuilds/linux-x64/libgmp.so.10 +0 -0
  84. package/prebuilds/linux-x64/libgnutls.so.30 +0 -0
  85. package/prebuilds/linux-x64/libhogweed.so.6 +0 -0
  86. package/prebuilds/linux-x64/libidn2.so.0 +0 -0
  87. package/prebuilds/linux-x64/libjsoncpp.so.25 +0 -0
  88. package/prebuilds/linux-x64/libnettle.so.8 +0 -0
  89. package/prebuilds/linux-x64/libopendht.so.4 +0 -0
  90. package/prebuilds/linux-x64/libp11-kit.so.0 +0 -0
  91. package/prebuilds/linux-x64/libtasn1.so.6 +0 -0
  92. package/prebuilds/linux-x64/libunistring.so.5 +0 -0
  93. package/prebuilds/linux-x64/licenses/OpenDHT-LICENSE.txt +7 -0
  94. package/prebuilds/linux-x64/licenses/libargon2-1-copyright.txt +167 -0
  95. package/prebuilds/linux-x64/licenses/libffi8-copyright.txt +225 -0
  96. package/prebuilds/linux-x64/licenses/libfmt9-copyright.txt +411 -0
  97. package/prebuilds/linux-x64/licenses/libgmp10-copyright.txt +94 -0
  98. package/prebuilds/linux-x64/licenses/libgnutls30t64-copyright.txt +1248 -0
  99. package/prebuilds/linux-x64/licenses/libhogweed6t64-copyright.txt +723 -0
  100. package/prebuilds/linux-x64/licenses/libidn2-0-copyright.txt +113 -0
  101. package/prebuilds/linux-x64/licenses/libjsoncpp25-copyright.txt +84 -0
  102. package/prebuilds/linux-x64/licenses/libnettle8t64-copyright.txt +723 -0
  103. package/prebuilds/linux-x64/licenses/libp11-kit0-copyright.txt +493 -0
  104. package/prebuilds/linux-x64/licenses/libtasn1-6-copyright.txt +83 -0
  105. package/prebuilds/linux-x64/licenses/libunistring5-copyright.txt +152 -0
  106. package/prebuilds/linux-x64/licenses/simdutf/LICENSE-APACHE +201 -0
  107. package/prebuilds/linux-x64/licenses/simdutf/LICENSE-MIT +18 -0
  108. package/prebuilds/linux-x64/manifest.json +21 -0
  109. package/prebuilds/linux-x64/node.napi.glibc.node +0 -0
  110. package/prebuilds/win32-x64/argon2.dll +0 -0
  111. package/prebuilds/win32-x64/fmt.dll +0 -0
  112. package/prebuilds/win32-x64/gmp-10.dll +0 -0
  113. package/prebuilds/win32-x64/gnutls.dll +0 -0
  114. package/prebuilds/win32-x64/hogweed-7.dll +0 -0
  115. package/prebuilds/win32-x64/jsoncpp.dll +0 -0
  116. package/prebuilds/win32-x64/licenses/OpenDHT-LICENSE.txt +7 -0
  117. package/prebuilds/win32-x64/manifest.json +18 -0
  118. package/prebuilds/win32-x64/nettle-9.dll +0 -0
  119. package/prebuilds/win32-x64/node.napi.node +0 -0
  120. package/prebuilds/win32-x64/opendht.dll +0 -0
  121. package/prebuilds/win32-x64/simdutf.dll +0 -0
  122. package/prebuilds/win32-x64/tasn1-6.dll +0 -0
package/README.md CHANGED
@@ -1,3 +1,255 @@
1
- # Temporary Holding Version
1
+ # OpenDHT Node.js Bindings
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Initial Node-API bindings using `node-addon-api` directly over the C++ library.
4
+ Node.js 22.9 or later is required; the addon targets Node-API version 8.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ npm install opendht
10
+ ```
11
+
12
+ ## Build
13
+
14
+ Install the native dependencies described in [BUILD.md](../BUILD.md), plus Node.js,
15
+ a C++17 compiler, and CMake 3.21 or later. Ninja is optional.
16
+
17
+ ```sh
18
+ cd nodejs
19
+ npm ci
20
+ npm run build
21
+ npm test
22
+ npm run typecheck
23
+ ```
24
+
25
+ CMake.js builds OpenDHT from the parent source directory in `nodejs/build/native`.
26
+ It does not change the repository's existing build directory. Tools, Python,
27
+ peer discovery, documentation, and native tests default to disabled in this build.
28
+ Native CMake options can be passed through, for example:
29
+
30
+ ```sh
31
+ npm run build -- --CDOPENDHT_PEER_DISCOVERY=ON
32
+ ```
33
+
34
+ The loader checks local builds, then compatible Node-API binaries under `prebuilds/`.
35
+ Set `OPENDHT_NODE_BINDING` to an absolute addon path to select an explicit build.
36
+ Packaged binaries include OpenDHT and non-system native dependencies, so archive
37
+ installation does not require a compiler or a system OpenDHT installation.
38
+
39
+ ## Example Tool
40
+
41
+ After building, start the TypeScript example from the repository root:
42
+
43
+ ```sh
44
+ npm --prefix nodejs run dhtnode -- --port 4222 --bootstrap bootstrap.jami.net
45
+ ```
46
+
47
+ The source is [examples/dhtnode.ts](examples/dhtnode.ts). `npm run build` compiles
48
+ it to JavaScript; run `npm run build:examples` after editing just the example.
49
+ Bootstrap is optional;
50
+ `--bootstrap-port` selects its UDP port. Use `--port 0` for a free local port.
51
+
52
+ ```text
53
+ listen greeting
54
+ put greeting hello world
55
+ get greeting
56
+ sign greeting signed hello
57
+ cancel greeting
58
+ quit
59
+ ```
60
+
61
+ Keys are text labels, hashed automatically; values are UTF-8 text. The tool
62
+ generates a fresh EC identity on each run and prints IPv4/IPv6 connectivity
63
+ changes. Operations run concurrently, leaving the prompt responsive; dependent
64
+ commands should be entered after their preceding operation completes. EOF waits
65
+ for pending operations, then cancels listeners and closes the runner. Ctrl-C,
66
+ SIGTERM, and `quit` close immediately, rejecting pending operations without
67
+ printing cancellation errors. `--help` lists all options. Archives include both
68
+ the TypeScript source and compiled `examples/dhtnode.js`, runnable without
69
+ TypeScript or development dependencies, including from inside `node_modules`.
70
+
71
+ ## Usage
72
+
73
+ ```js
74
+ import { DhtRunner, hash } from 'opendht';
75
+
76
+ async function main() {
77
+ const writer = new DhtRunner();
78
+ const reader = new DhtRunner();
79
+ try {
80
+ writer.run({ port: 0, ipv4: '127.0.0.1', ipv6: '::1' });
81
+ reader.run({ port: 0, ipv4: '127.0.0.1', ipv6: '::1' });
82
+ writer.bootstrap('127.0.0.1', reader.getBoundPort());
83
+ reader.bootstrap('127.0.0.1', writer.getBoundPort());
84
+ const key = hash('example');
85
+ const stored = await writer.put(key, Buffer.from('hello'), { id: 42n });
86
+ if (!stored) throw new Error('DHT put failed');
87
+ for (const value of await reader.get(key)) {
88
+ console.log(value.id, value.data.toString());
89
+ }
90
+ } finally {
91
+ await Promise.all([writer.close(), reader.close()]);
92
+ }
93
+ }
94
+
95
+ main().catch(console.error);
96
+ ```
97
+
98
+ ## API
99
+
100
+ - `hash(string | Uint8Array)` returns a SHA-1 hash as a 40-character hex string.
101
+ All get/put/listen keys must be hex hashes, not unhashed application keys.
102
+ - `version` is the underlying OpenDHT version.
103
+ - `run({port, ipv4, ipv6, network, persistPath, identity})` starts a threaded node. Port 0
104
+ selects a free port. The defaults bind both IP families on all interfaces.
105
+ `persistPath` is optional; use an empty string to disable persistence.
106
+ - `getBoundPort(4 | 6)` defaults to IPv4; `getNodeId()` returns the node's hex ID.
107
+ - `getStatus()` returns the latest JS-dispatched `{ipv4, ipv6}` connectivity
108
+ snapshot. Each family is `'disconnected'`, `'connecting'`, or `'connected'`.
109
+ `runner.on('statusChanged', status => {})` receives changes on the JS thread.
110
+ New and closing/closed runners report both families as disconnected. No status
111
+ events are delivered after close begins; close does not emit a final event.
112
+ - `bootstrap(host, port)` queues bootstrap discovery. Returning does not mean the
113
+ peer is connected; subsequent DHT operations report their own completion.
114
+ - `put(key, Uint8Array, {id, type, userType, permanent})` copies the input and
115
+ resolves to the native success boolean. IDs are unsigned 64-bit `bigint` values.
116
+ - `get(key)` resolves to value snapshots, or rejects with `ERR_DHT_GET_FAILED`.
117
+ Values contain `id`, `type`, `seq`, `userType`, copied `Buffer` data, `isSigned`,
118
+ `isEncrypted`, and an `owner` long fingerprint (or null for unsigned values).
119
+ - `listen(key, (value, expired) => {})` returns a listener with idempotent
120
+ `cancel()`. Queued deliveries are suppressed after cancellation. Callback
121
+ return values are ignored; callbacks may cancel or close the runner.
122
+ - `close()` is idempotent and returns the same promise on repeated calls. It
123
+ waits off the JS thread for graceful shutdown, then joins the native threads.
124
+ After two seconds it forces the join if graceful shutdown has not completed.
125
+ Pending operations reject with `ERR_DHT_CLOSED`. A closed runner cannot restart.
126
+ - `ref()` and `unref()` control whether the runner keeps Node's event loop alive.
127
+ Running nodes are referenced by default. `Symbol.asyncDispose` calls `close()`.
128
+
129
+ Callbacks run only on their owning JS thread. There is no polling timer or worker
130
+ thread waiting on each get/put. Explicitly close runners; GC cleanup and Node
131
+ environment cleanup hooks are fallbacks, including forced worker termination.
132
+ Pending operations, active listeners, and registered status handlers keep their
133
+ runner alive until completion, cancellation, handler removal, or explicit close.
134
+ Graceful persistence cannot be guaranteed if the process is killed.
135
+
136
+ The binding does not cap the callback queue or accumulated get results. Queued
137
+ callbacks retain their native values until delivery or cleanup.
138
+
139
+ ## Crypto
140
+
141
+ `PrivateKey.generate(options)` and `Identity.generate(name, options)` return
142
+ promises and generate keys off the JS thread. Options accept `algorithm: 'ec'`
143
+ (the default, using OpenDHT's default EC curve) or `'rsa'`. RSA `bits` must be an
144
+ integer between 2048 and 8192; the default is 2048.
145
+
146
+ - `new PrivateKey(bytes, password?)` imports PEM/DER; `serialize(password?)`
147
+ exports PKCS#8 PEM. A nonempty password encrypts the exported key.
148
+ - `privateKey.getPublicKey()` returns an owned public key. `sign(bytes)` and
149
+ `decrypt(bytes)` return copied Buffers.
150
+ - `new PublicKey(bytes)` imports a public key; `serialize()` exports DER.
151
+ `checkSignature(data, signature)` returns a boolean. `encrypt(bytes)` requires
152
+ an RSA key; EC keys support signatures, not this encryption scheme.
153
+ - `new Certificate(bytes)` imports PEM/DER or a PEM certificate chain;
154
+ `serialize()` exports a PEM chain. Import does not establish trust or validate
155
+ the chain against a trust store. `getPublicKey()` returns its public key.
156
+ - Public keys and certificates expose `getId()` (40 hex characters) and
157
+ `getLongId()` (64 hex characters).
158
+ - `new Identity(privateKey, certificate)` requires matching fingerprints.
159
+ Its read-only `privateKey` and `certificate` properties return owned wrappers.
160
+ - Pass `identity` to `run()` to enable `putSigned(key, data, options?)` and
161
+ `putEncrypted(key, data, recipientPublicKey, options?)`. Both return the same
162
+ success boolean as `put()`. Encrypted values are signed by the sender and
163
+ transparently decrypted for the recipient by OpenDHT's get/listen layer.
164
+
165
+ ```js
166
+ import { Identity, DhtRunner } from 'opendht';
167
+
168
+ async function createAuthenticatedNode() {
169
+ const identity = await Identity.generate('example', { algorithm: 'rsa', bits: 2048 });
170
+ const runner = new DhtRunner();
171
+ runner.run({ port: 0, identity });
172
+ return { runner, identity };
173
+ }
174
+ ```
175
+
176
+ Crypto methods take Uint8Array/Buffer inputs, not implicit text encodings. Imports
177
+ must be nonempty. Malformed handles/data,
178
+ mismatched identities, and unsupported encryption keys raise JS exceptions.
179
+ Only generation is asynchronous; import/export/sign/encrypt/decrypt are
180
+ synchronous and should be used from worker threads for large workloads.
181
+
182
+ ## Packaging And CI
183
+
184
+ From a successful Release build:
185
+
186
+ ```sh
187
+ npm run package
188
+ npm run test:package
189
+ ```
190
+
191
+ `bundle` copies the addon into `prebuilds/<platform>-<arch>/`, gathers its runtime
192
+ dependencies, rewrites native loader paths, and copies dependency license
193
+ notices. macOS needs `dylibbundler` and Apple developer tools; Linux needs
194
+ `patchelf` and Debian/Ubuntu dependency copyright files. Windows uses the vcpkg
195
+ installed tree (`VCPKG_INSTALLED_DIR`, `VCPKG_DEFAULT_TRIPLET`) and MSVC tools.
196
+ `OPENDHT_LIBRARY_PATH` adds native library search directories when bundling.
197
+ An explicit addon path may be passed to `npm run bundle -- /absolute/addon.node`.
198
+ Bundling replaces only the current platform's generated prebuild directory.
199
+
200
+ `test:package` creates an npm archive, installs it in a temporary consumer with
201
+ install scripts disabled and no dev dependencies, forces prebuild-only loading,
202
+ and runs the full runtime suite. Pass an archive file or a directory containing
203
+ one archive to test it directly, for example `npm run test:package -- dist`.
204
+ Only runtime JS, declarations, the example's TypeScript source, documentation,
205
+ and prebuilds are included in the archive. `prepack` compiles the example, so
206
+ archive creation needs the development dependencies; archive installation does not.
207
+
208
+ The [Node.js package workflow](../.github/workflows/nodejs-package.yml) builds:
209
+
210
+ | Target | Build Baseline |
211
+ | --- | --- |
212
+ | Linux x64 | Ubuntu 24.04 / glibc 2.39 (Noble dependency image) |
213
+ | macOS ARM64 and x64 | macOS 15 |
214
+ | Windows x64 | Windows Server 2022 / MSVC |
215
+
216
+ The Linux build uses `ghcr.io/savoirfairelinux/opendht/opendht-deps-noble`,
217
+ built from [the Noble Dockerfile](../docker/DockerfileDepsNoble), restored from
218
+ the Ubuntu 24.04 recipe in git history. The release workflow publishes this
219
+ multi-architecture image alongside the other Docker images. Node builds use its
220
+ published `latest` tag. simdutf is linked statically because Ubuntu 24.04 does not
221
+ provide its development package.
222
+
223
+ CI combines platform prebuilds into one npm archive and verifies that archive on
224
+ Node 22, 24, and 26 on each platform, including Ubuntu 24.04 and 26.04. Branch
225
+ pushes, pull requests, and manual runs build and test without publishing.
226
+ musl/Alpine and other architectures are not currently built. Node-API stability
227
+ does not remove OS/libc or native dependency compatibility requirements. Review
228
+ the included dependency licenses and source-distribution obligations before
229
+ redistributing binaries.
230
+
231
+ ## Releases
232
+
233
+ Pushing a `v*` tag starts [the release workflow](../.github/workflows/release-package.yml),
234
+ which calls the Node.js package workflow. The npm archive version is taken from
235
+ the tag without its leading `v`, for example `v4.4.99` becomes `opendht@4.4.99`.
236
+ After all Node install tests and Windows builds pass, the release workflow attaches
237
+ the verified npm archive alongside the Windows assets to the draft GitHub Release,
238
+ then publishes that same archive to npm with provenance. Stable versions use the
239
+ `latest` dist-tag; prerelease versions such as `v4.5.0-rc.1` use `next`.
240
+ Publishing to npm happens on the tag push, not when the GitHub draft is published.
241
+ Published npm versions cannot be overwritten; use a new version tag for changes.
242
+
243
+ Configure an npm trusted publisher for the `opendht` package with GitHub owner
244
+ `savoirfairelinux`, repository `opendht`, and workflow filename `release-package.yml`
245
+ (not `nodejs-package.yml`). Allow direct `npm publish`. Publication runs on a
246
+ GitHub-hosted runner with OIDC, so no npm token is needed once this is configured.
247
+
248
+ For the first publication, before the npm package exists, set the repository's
249
+ `NPM_TOKEN` secret to a granular npm token with publishing permission and 2FA
250
+ bypass. After the first successful tag release, configure the trusted publisher
251
+ in the npm package settings, then remove `NPM_TOKEN`. The publishing job supports
252
+ the token for this bootstrap and prefers OIDC when available.
253
+
254
+ Query filters, async iterators, AbortSignal support, certificate trust-store
255
+ validation, CA issuance controls, and proxy controls remain future work.
package/crypto.js ADDED
@@ -0,0 +1,56 @@
1
+ export default function createCrypto(native) {
2
+ const handles = new WeakMap();
3
+
4
+ function handle(value, Type) {
5
+ if (!(value instanceof Type) || !handles.has(value)) throw new TypeError(`Expected ${Type.name}`);
6
+ return handles.get(value);
7
+ }
8
+
9
+ function wrap(Type, nativeHandle) {
10
+ const result = Object.create(Type.prototype);
11
+ handles.set(result, nativeHandle);
12
+ return result;
13
+ }
14
+
15
+ function generate(kind, name, options = {}) {
16
+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Invalid crypto options');
17
+ return native.cryptoGenerate(kind, name, options.algorithm ?? 'ec', options.bits ?? 2048);
18
+ }
19
+
20
+ class PublicKey {
21
+ constructor(data) { handles.set(this, native.cryptoImport('public', data)); }
22
+ serialize() { return native.cryptoSerialize(handle(this, PublicKey)); }
23
+ getId() { return native.cryptoId(handle(this, PublicKey), false); }
24
+ getLongId() { return native.cryptoId(handle(this, PublicKey), true); }
25
+ checkSignature(data, signature) { return native.cryptoVerify(handle(this, PublicKey), data, signature); }
26
+ encrypt(data) { return native.cryptoEncrypt(handle(this, PublicKey), data); }
27
+ }
28
+
29
+ class PrivateKey {
30
+ constructor(data, password = '') { handles.set(this, native.cryptoImport('private', data, password)); }
31
+ static generate(options) { return generate('private', '', options).then(value => wrap(PrivateKey, value)); }
32
+ serialize(password = '') { return native.cryptoSerialize(handle(this, PrivateKey), password); }
33
+ getPublicKey() { return wrap(PublicKey, native.cryptoPublicKey(handle(this, PrivateKey))); }
34
+ sign(data) { return native.cryptoSign(handle(this, PrivateKey), data); }
35
+ decrypt(data) { return native.cryptoDecrypt(handle(this, PrivateKey), data); }
36
+ }
37
+
38
+ class Certificate {
39
+ constructor(data) { handles.set(this, native.cryptoImport('certificate', data)); }
40
+ serialize() { return native.cryptoSerialize(handle(this, Certificate)); }
41
+ getPublicKey() { return wrap(PublicKey, native.cryptoPublicKey(handle(this, Certificate))); }
42
+ getId() { return native.cryptoId(handle(this, Certificate), false); }
43
+ getLongId() { return native.cryptoId(handle(this, Certificate), true); }
44
+ }
45
+
46
+ class Identity {
47
+ constructor(privateKey, certificate) {
48
+ handles.set(this, native.cryptoIdentity(handle(privateKey, PrivateKey), handle(certificate, Certificate)));
49
+ }
50
+ static generate(name = 'dhtnode', options) { return generate('identity', name, options).then(value => wrap(Identity, value)); }
51
+ get privateKey() { return wrap(PrivateKey, native.cryptoIdentityPart(handle(this, Identity), true)); }
52
+ get certificate() { return wrap(Certificate, native.cryptoIdentityPart(handle(this, Identity), false)); }
53
+ }
54
+
55
+ return { PublicKey, PrivateKey, Certificate, Identity, handle };
56
+ }
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ import { clearLine, createInterface, cursorTo } from 'node:readline';
3
+ import { parseArgs } from 'node:util';
4
+ const commands = 'get KEY | put KEY TEXT | sign KEY TEXT | listen KEY | cancel KEY | help | quit';
5
+ function portNumber(value, name, minimum = 0) {
6
+ const port = Number(value);
7
+ if (!Number.isInteger(port) || port < minimum || port > 65535) {
8
+ throw new Error(`${name} must be an integer between ${minimum} and 65535`);
9
+ }
10
+ return port;
11
+ }
12
+ function errorMessage(error) {
13
+ return error instanceof Error ? error.message : String(error);
14
+ }
15
+ function report(error) {
16
+ console.error(errorMessage(error));
17
+ process.exitCode = 1;
18
+ }
19
+ async function main() {
20
+ const { values } = parseArgs({
21
+ options: {
22
+ help: { type: 'boolean', short: 'h' },
23
+ port: { type: 'string', short: 'p', default: '4222' },
24
+ ipv4: { type: 'string', default: '0.0.0.0' },
25
+ ipv6: { type: 'string', default: '::' },
26
+ bootstrap: { type: 'string', short: 'b' },
27
+ 'bootstrap-port': { type: 'string', default: '4222' },
28
+ },
29
+ });
30
+ if (values.help) {
31
+ console.log(`Usage: npm run dhtnode -- [options]
32
+
33
+ -p, --port PORT Local UDP port (default: 4222; 0 selects a free port)
34
+ -b, --bootstrap HOST Optional bootstrap hostname or IP address
35
+ --bootstrap-port PORT Bootstrap UDP port (default: 4222)
36
+ --ipv4 ADDRESS IPv4 bind address (default: 0.0.0.0)
37
+ --ipv6 ADDRESS IPv6 bind address (default: ::)
38
+ -h, --help Show help
39
+
40
+ Commands: ${commands}
41
+ Keys are text labels hashed with SHA-1. Values are UTF-8 text.`);
42
+ return;
43
+ }
44
+ const port = portNumber(values.port, 'port');
45
+ const bootstrapPort = portNumber(values['bootstrap-port'], 'bootstrap-port', 1);
46
+ const { DhtRunner, Identity, hash } = await import('../index.js');
47
+ const identity = await Identity.generate('dhtnode.ts');
48
+ const runner = new DhtRunner();
49
+ const listeners = new Map();
50
+ const pending = new Set();
51
+ let lines;
52
+ let closing;
53
+ function close() {
54
+ if (!closing) {
55
+ for (const listener of listeners.values())
56
+ listener.cancel();
57
+ listeners.clear();
58
+ lines?.close();
59
+ closing = runner.close();
60
+ }
61
+ return closing;
62
+ }
63
+ function print(message) {
64
+ if (process.stdout.isTTY && lines) {
65
+ clearLine(process.stdout, 0);
66
+ cursorTo(process.stdout, 0);
67
+ }
68
+ console.log(message);
69
+ if (!closing && process.stdin.isTTY)
70
+ lines?.prompt(true);
71
+ }
72
+ const stop = () => { close().catch(report); };
73
+ const printValue = (label, value) => {
74
+ print(`${label} ${value.id}: ${JSON.stringify(value.data.toString('utf8'))}${value.isSigned ? ' [signed]' : ''}`);
75
+ };
76
+ const printStatus = (status) => {
77
+ print(`Connectivity: IPv4 ${status.ipv4}, IPv6 ${status.ipv6}`);
78
+ };
79
+ async function execute(line) {
80
+ const [, command, key, data] = line.trim().match(/^(\S+)(?:\s+(\S+))?(?:\s+(.+))?$/) || [];
81
+ if (!command)
82
+ return;
83
+ if (command === 'help') {
84
+ print(commands);
85
+ return;
86
+ }
87
+ if (!key)
88
+ throw new Error('Expected a key. Type help for commands.');
89
+ const location = hash(key);
90
+ switch (command) {
91
+ case 'get': {
92
+ const found = await runner.get(location);
93
+ if (closing)
94
+ return;
95
+ for (const value of found)
96
+ printValue(key, value);
97
+ if (!found.length)
98
+ print(`No values for ${key}`);
99
+ break;
100
+ }
101
+ case 'put':
102
+ case 'sign': {
103
+ if (data === undefined)
104
+ throw new Error(`Usage: ${command} KEY TEXT`);
105
+ const payload = Buffer.from(data, 'utf8');
106
+ const ok = command === 'sign' ? await runner.putSigned(location, payload)
107
+ : await runner.put(location, payload);
108
+ if (closing)
109
+ return;
110
+ if (!ok)
111
+ throw new Error(`Put failed for ${key}`);
112
+ print(`Stored ${key}`);
113
+ break;
114
+ }
115
+ case 'listen':
116
+ if (!listeners.has(key)) {
117
+ listeners.set(key, runner.listen(location, (value, expired) => {
118
+ printValue(`${expired ? 'Expired' : 'Value'} ${key}`, value);
119
+ }));
120
+ }
121
+ print(`Listening ${key}`);
122
+ break;
123
+ case 'cancel':
124
+ listeners.get(key)?.cancel();
125
+ listeners.delete(key);
126
+ print(`Cancelled ${key}`);
127
+ break;
128
+ default:
129
+ throw new Error('Unknown command. Type help for commands.');
130
+ }
131
+ }
132
+ runner.on('error', error => { report(error); stop(); });
133
+ runner.on('statusChanged', printStatus);
134
+ process.on('SIGINT', stop);
135
+ process.on('SIGTERM', stop);
136
+ try {
137
+ runner.run({ port, ipv4: values.ipv4, ipv6: values.ipv6, identity });
138
+ if (values.bootstrap)
139
+ runner.bootstrap(values.bootstrap, bootstrapPort);
140
+ lines = createInterface({ input: process.stdin, output: process.stdout });
141
+ lines.on('SIGINT', stop);
142
+ lines.setPrompt('dht> ');
143
+ print(`Node ${runner.getNodeId()} listening on UDP ${runner.getBoundPort()}`);
144
+ printStatus(runner.getStatus());
145
+ if (process.stdin.isTTY)
146
+ print(commands);
147
+ for await (const line of lines) {
148
+ if (closing)
149
+ break;
150
+ if (/^(quit|exit)(?:\s|$)/.test(line.trim())) {
151
+ stop();
152
+ break;
153
+ }
154
+ const operation = execute(line).catch(error => {
155
+ if (!closing)
156
+ console.error(errorMessage(error));
157
+ }).finally(() => { pending.delete(operation); });
158
+ pending.add(operation);
159
+ if (process.stdin.isTTY)
160
+ lines.prompt();
161
+ }
162
+ if (!closing)
163
+ await Promise.all(pending);
164
+ }
165
+ finally {
166
+ try {
167
+ await close();
168
+ await Promise.all(pending);
169
+ }
170
+ finally {
171
+ process.removeListener('SIGINT', stop);
172
+ process.removeListener('SIGTERM', stop);
173
+ }
174
+ }
175
+ }
176
+ main().catch(report);
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { clearLine, createInterface, cursorTo, type Interface } from 'node:readline';
4
+ import { parseArgs } from 'node:util';
5
+ import type { ConnectivityStatus, Listener, Value } from '../index.js';
6
+
7
+ const commands = 'get KEY | put KEY TEXT | sign KEY TEXT | listen KEY | cancel KEY | help | quit';
8
+
9
+ function portNumber(value: string, name: string, minimum = 0): number {
10
+ const port = Number(value);
11
+ if (!Number.isInteger(port) || port < minimum || port > 65535) {
12
+ throw new Error(`${name} must be an integer between ${minimum} and 65535`);
13
+ }
14
+ return port;
15
+ }
16
+
17
+ function errorMessage(error: unknown): string {
18
+ return error instanceof Error ? error.message : String(error);
19
+ }
20
+
21
+ function report(error: unknown): void {
22
+ console.error(errorMessage(error));
23
+ process.exitCode = 1;
24
+ }
25
+
26
+ async function main(): Promise<void> {
27
+ const { values } = parseArgs({
28
+ options: {
29
+ help: { type: 'boolean', short: 'h' },
30
+ port: { type: 'string', short: 'p', default: '4222' },
31
+ ipv4: { type: 'string', default: '0.0.0.0' },
32
+ ipv6: { type: 'string', default: '::' },
33
+ bootstrap: { type: 'string', short: 'b' },
34
+ 'bootstrap-port': { type: 'string', default: '4222' },
35
+ },
36
+ });
37
+ if (values.help) {
38
+ console.log(`Usage: npm run dhtnode -- [options]
39
+
40
+ -p, --port PORT Local UDP port (default: 4222; 0 selects a free port)
41
+ -b, --bootstrap HOST Optional bootstrap hostname or IP address
42
+ --bootstrap-port PORT Bootstrap UDP port (default: 4222)
43
+ --ipv4 ADDRESS IPv4 bind address (default: 0.0.0.0)
44
+ --ipv6 ADDRESS IPv6 bind address (default: ::)
45
+ -h, --help Show help
46
+
47
+ Commands: ${commands}
48
+ Keys are text labels hashed with SHA-1. Values are UTF-8 text.`);
49
+ return;
50
+ }
51
+ const port = portNumber(values.port, 'port');
52
+ const bootstrapPort = portNumber(values['bootstrap-port'], 'bootstrap-port', 1);
53
+ const { DhtRunner, Identity, hash } = await import('../index.js');
54
+ const identity = await Identity.generate('dhtnode.ts');
55
+ const runner = new DhtRunner();
56
+ const listeners = new Map<string, Listener>();
57
+ const pending = new Set<Promise<void>>();
58
+ let lines: Interface | undefined;
59
+ let closing: Promise<void> | undefined;
60
+
61
+ function close(): Promise<void> {
62
+ if (!closing) {
63
+ for (const listener of listeners.values()) listener.cancel();
64
+ listeners.clear();
65
+ lines?.close();
66
+ closing = runner.close();
67
+ }
68
+ return closing;
69
+ }
70
+
71
+ function print(message: string): void {
72
+ if (process.stdout.isTTY && lines) {
73
+ clearLine(process.stdout, 0);
74
+ cursorTo(process.stdout, 0);
75
+ }
76
+ console.log(message);
77
+ if (!closing && process.stdin.isTTY) lines?.prompt(true);
78
+ }
79
+
80
+ const stop = (): void => { close().catch(report); };
81
+ const printValue = (label: string, value: Value): void => {
82
+ print(`${label} ${value.id}: ${JSON.stringify(value.data.toString('utf8'))}${value.isSigned ? ' [signed]' : ''}`);
83
+ };
84
+ const printStatus = (status: ConnectivityStatus): void => {
85
+ print(`Connectivity: IPv4 ${status.ipv4}, IPv6 ${status.ipv6}`);
86
+ };
87
+
88
+ async function execute(line: string): Promise<void> {
89
+ const [, command, key, data] = line.trim().match(/^(\S+)(?:\s+(\S+))?(?:\s+(.+))?$/) || [];
90
+ if (!command) return;
91
+ if (command === 'help') {
92
+ print(commands);
93
+ return;
94
+ }
95
+ if (!key) throw new Error('Expected a key. Type help for commands.');
96
+ const location = hash(key);
97
+ switch (command) {
98
+ case 'get': {
99
+ const found = await runner.get(location);
100
+ if (closing) return;
101
+ for (const value of found) printValue(key, value);
102
+ if (!found.length) print(`No values for ${key}`);
103
+ break;
104
+ }
105
+ case 'put':
106
+ case 'sign': {
107
+ if (data === undefined) throw new Error(`Usage: ${command} KEY TEXT`);
108
+ const payload = Buffer.from(data, 'utf8');
109
+ const ok = command === 'sign' ? await runner.putSigned(location, payload)
110
+ : await runner.put(location, payload);
111
+ if (closing) return;
112
+ if (!ok) throw new Error(`Put failed for ${key}`);
113
+ print(`Stored ${key}`);
114
+ break;
115
+ }
116
+ case 'listen':
117
+ if (!listeners.has(key)) {
118
+ listeners.set(key, runner.listen(location, (value, expired) => {
119
+ printValue(`${expired ? 'Expired' : 'Value'} ${key}`, value);
120
+ }));
121
+ }
122
+ print(`Listening ${key}`);
123
+ break;
124
+ case 'cancel':
125
+ listeners.get(key)?.cancel();
126
+ listeners.delete(key);
127
+ print(`Cancelled ${key}`);
128
+ break;
129
+ default:
130
+ throw new Error('Unknown command. Type help for commands.');
131
+ }
132
+ }
133
+
134
+ runner.on('error', error => { report(error); stop(); });
135
+ runner.on('statusChanged', printStatus);
136
+ process.on('SIGINT', stop);
137
+ process.on('SIGTERM', stop);
138
+ try {
139
+ runner.run({ port, ipv4: values.ipv4, ipv6: values.ipv6, identity });
140
+ if (values.bootstrap) runner.bootstrap(values.bootstrap, bootstrapPort);
141
+ lines = createInterface({ input: process.stdin, output: process.stdout });
142
+ lines.on('SIGINT', stop);
143
+ lines.setPrompt('dht> ');
144
+ print(`Node ${runner.getNodeId()} listening on UDP ${runner.getBoundPort()}`);
145
+ printStatus(runner.getStatus());
146
+ if (process.stdin.isTTY) print(commands);
147
+ for await (const line of lines) {
148
+ if (closing) break;
149
+ if (/^(quit|exit)(?:\s|$)/.test(line.trim())) {
150
+ stop();
151
+ break;
152
+ }
153
+ const operation = execute(line).catch(error => {
154
+ if (!closing) console.error(errorMessage(error));
155
+ }).finally(() => { pending.delete(operation); });
156
+ pending.add(operation);
157
+ if (process.stdin.isTTY) lines.prompt();
158
+ }
159
+ if (!closing) await Promise.all(pending);
160
+ } finally {
161
+ try {
162
+ await close();
163
+ await Promise.all(pending);
164
+ } finally {
165
+ process.removeListener('SIGINT', stop);
166
+ process.removeListener('SIGTERM', stop);
167
+ }
168
+ }
169
+ }
170
+
171
+ main().catch(report);