@ghostlytools/cli 1.11.1 → 1.11.3

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 (107) hide show
  1. package/README.md +32 -23
  2. package/dist/assets/{api-DL0Uazf6.js → api-DBlaoz8i.js} +478 -141
  3. package/dist/assets/api-DBlaoz8i.js.map +1 -0
  4. package/dist/assets/{api-D89ubgas.js → api-DgU4MZPD.js} +2 -2
  5. package/dist/assets/{apiKit-D78MXTrk.js → apiKit-DesObIDf.js} +19 -9
  6. package/dist/assets/apiKit-DesObIDf.js.map +1 -0
  7. package/dist/assets/appFetch-C8yZIq1e.js +194 -0
  8. package/dist/assets/appFetch-C8yZIq1e.js.map +1 -0
  9. package/dist/assets/{apps--pAqmfgQ.js → apps-DkMjDHML.js} +142 -67
  10. package/dist/assets/apps-DkMjDHML.js.map +1 -0
  11. package/dist/assets/{apps-BlSl1nGn.js → apps-rzxsjfBV.js} +1 -1
  12. package/dist/assets/{arkade-DxB-MR43.js → arkade-CarKONmH.js} +2 -2
  13. package/dist/assets/{arkade-DxB-MR43.js.map → arkade-CarKONmH.js.map} +1 -1
  14. package/dist/assets/{backup-B3JJd75o.js → backup-C0OJCJlM.js} +90 -47
  15. package/dist/assets/backup-C0OJCJlM.js.map +1 -0
  16. package/dist/assets/{backup-T7gFpU80.js → backup-CgWU7x0T.js} +1 -1
  17. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  18. package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
  19. package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
  20. package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
  21. package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
  22. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  23. package/dist/assets/buttons-Cco0Agfa.js +2 -0
  24. package/dist/assets/{buttons-C1VbDihe.js → buttons-fZTEa_2i.js} +47 -7
  25. package/dist/assets/buttons-fZTEa_2i.js.map +1 -0
  26. package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
  27. package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
  28. package/dist/assets/{client-CGLuWFRV.js → client-Ibk3-e60.js} +31 -3
  29. package/dist/assets/client-Ibk3-e60.js.map +1 -0
  30. package/dist/assets/{codec-YGJDr7uH.js → codec-DMpQqVSt.js} +2 -2
  31. package/dist/assets/{codec-YGJDr7uH.js.map → codec-DMpQqVSt.js.map} +1 -1
  32. package/dist/assets/endpoint-DarqblYE.js +5052 -0
  33. package/dist/assets/endpoint-DarqblYE.js.map +1 -0
  34. package/dist/assets/{envelope-Dwq8EN8x.js → envelope-CvQVCGdf.js} +2 -2
  35. package/dist/assets/{envelope-Dwq8EN8x.js.map → envelope-CvQVCGdf.js.map} +1 -1
  36. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-zV_5Qdqz.js} +6 -3
  37. package/dist/assets/fedimintSdk-zV_5Qdqz.js.map +1 -0
  38. package/dist/assets/{fixedHosts-CINXidpd.js → fixedHosts-6gKn8dp2.js} +3 -3
  39. package/dist/assets/{fixedHosts-CINXidpd.js.map → fixedHosts-6gKn8dp2.js.map} +1 -1
  40. package/dist/assets/{host-CGlHkiQv.js → host-CYlIiY3r.js} +455 -104
  41. package/dist/assets/host-CYlIiY3r.js.map +1 -0
  42. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js → hyperdhtRelay-CdsLcAhY.js} +2 -2
  43. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js.map → hyperdhtRelay-CdsLcAhY.js.map} +1 -1
  44. package/dist/assets/{irohWeb-CYn0uB_A.js → irohWeb-D2IuloLL.js} +705 -43
  45. package/dist/assets/irohWeb-D2IuloLL.js.map +1 -0
  46. package/dist/assets/jsonOut-POtMBS_V.js +16 -0
  47. package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
  48. package/dist/assets/{main-CgLW_Gyx.js → main-C0PfjKTe.js} +263 -128
  49. package/dist/assets/main-C0PfjKTe.js.map +1 -0
  50. package/dist/assets/{mainline-B0h8RchD.js → mainline-Cu61qcPS.js} +60 -24
  51. package/dist/assets/mainline-Cu61qcPS.js.map +1 -0
  52. package/dist/assets/{networkReason-BBosp2KG.js → networkReason-Dt7Yx_n4.js} +3 -3
  53. package/dist/assets/{networkReason-BBosp2KG.js.map → networkReason-Dt7Yx_n4.js.map} +1 -1
  54. package/dist/assets/{nwc-SSNS1aJ-.js → nwc-CtZypDcv.js} +6 -5
  55. package/dist/assets/nwc-CtZypDcv.js.map +1 -0
  56. package/dist/assets/{nwcProvider-BXqJmM98.js → nwcProvider-DYHkd0iu.js} +6 -3
  57. package/dist/assets/{nwcProvider-BXqJmM98.js.map → nwcProvider-DYHkd0iu.js.map} +1 -1
  58. package/dist/assets/{ownDid--DtH_Jdi.js → ownDid-CJ0ta8CL.js} +3 -3
  59. package/dist/assets/{ownDid--DtH_Jdi.js.map → ownDid-CJ0ta8CL.js.map} +1 -1
  60. package/dist/assets/{ownStatus-CQPGjCUR.js → ownStatus-D4HC6tNR.js} +12 -6
  61. package/dist/assets/{ownStatus-CQPGjCUR.js.map → ownStatus-D4HC6tNR.js.map} +1 -1
  62. package/dist/assets/{profiles-4UQ1Hsds.js → profiles-Ccdq6Xf6.js} +82 -6
  63. package/dist/assets/profiles-Ccdq6Xf6.js.map +1 -0
  64. package/dist/assets/{registry-B6BXKv6Q.js → registry-CE0PpQAE.js} +1 -1
  65. package/dist/assets/{registry-BKCFTEYp.js → registry-LvxsLJ5S.js} +88 -25
  66. package/dist/assets/registry-LvxsLJ5S.js.map +1 -0
  67. package/dist/assets/{resolve-MFeFljsN.js → resolve-6kVu2DE5.js} +4 -3
  68. package/dist/assets/resolve-6kVu2DE5.js.map +1 -0
  69. package/dist/assets/{server-rHKhnog1.js → server-Q3VcNqGt.js} +630 -933
  70. package/dist/assets/server-Q3VcNqGt.js.map +1 -0
  71. package/dist/assets/{src-BzsyAvPf.js → src-DjVj2ynY.js} +580 -168
  72. package/dist/assets/src-DjVj2ynY.js.map +1 -0
  73. package/dist/assets/{sshForges-qITn-RoV.js → sshForges-DeZ9cN9Q.js} +4 -3
  74. package/dist/assets/sshForges-DeZ9cN9Q.js.map +1 -0
  75. package/dist/assets/{translate-Bkr_iDgp.js → translate-iQZq4TnY.js} +36 -15
  76. package/dist/assets/translate-iQZq4TnY.js.map +1 -0
  77. package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
  78. package/dist/assets/types-Clyb52K2.js.map +1 -0
  79. package/dist/assets/{usdt-Bp7T2iqt.js → usdt-DnyTGdTX.js} +3 -3
  80. package/dist/assets/{usdt-Bp7T2iqt.js.map → usdt-DnyTGdTX.js.map} +1 -1
  81. package/dist/ghostly.mjs +1 -1
  82. package/npm-shrinkwrap.json +3592 -0
  83. package/package.json +5 -3
  84. package/dist/assets/api-DL0Uazf6.js.map +0 -1
  85. package/dist/assets/apiKit-D78MXTrk.js.map +0 -1
  86. package/dist/assets/apps--pAqmfgQ.js.map +0 -1
  87. package/dist/assets/backup-B3JJd75o.js.map +0 -1
  88. package/dist/assets/buttons-C1VbDihe.js.map +0 -1
  89. package/dist/assets/buttons-DwWuK_uN.js +0 -2
  90. package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
  91. package/dist/assets/client-CGLuWFRV.js.map +0 -1
  92. package/dist/assets/endpoint-DWHkXWVM.js +0 -419
  93. package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
  94. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
  95. package/dist/assets/host-CGlHkiQv.js.map +0 -1
  96. package/dist/assets/irohWeb-CYn0uB_A.js.map +0 -1
  97. package/dist/assets/main-CgLW_Gyx.js.map +0 -1
  98. package/dist/assets/mainline-B0h8RchD.js.map +0 -1
  99. package/dist/assets/nwc-SSNS1aJ-.js.map +0 -1
  100. package/dist/assets/profiles-4UQ1Hsds.js.map +0 -1
  101. package/dist/assets/registry-BKCFTEYp.js.map +0 -1
  102. package/dist/assets/resolve-MFeFljsN.js.map +0 -1
  103. package/dist/assets/server-rHKhnog1.js.map +0 -1
  104. package/dist/assets/src-BzsyAvPf.js.map +0 -1
  105. package/dist/assets/sshForges-qITn-RoV.js.map +0 -1
  106. package/dist/assets/translate-Bkr_iDgp.js.map +0 -1
  107. package/dist/assets/types-C4_KafL_.js.map +0 -1
@@ -0,0 +1,5052 @@
1
+ import { createRequire } from "node:module";
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: true
23
+ }) : target, mod));
24
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
25
+ //#endregion
26
+ //#region ../../node_modules/hyperdht/lib/messages.js
27
+ var require_messages = /* @__PURE__ */ __commonJSMin(((exports) => {
28
+ var c$5 = __require("compact-encoding");
29
+ var ipv4 = {
30
+ ...c$5.ipv4Address,
31
+ decode(state) {
32
+ const ip = c$5.ipv4Address.decode(state);
33
+ return {
34
+ host: ip.host,
35
+ port: ip.port
36
+ };
37
+ }
38
+ };
39
+ var ipv4Array = c$5.array(ipv4);
40
+ var ipv6 = {
41
+ ...c$5.ipv6Address,
42
+ decode(state) {
43
+ const ip = c$5.ipv6Address.decode(state);
44
+ return {
45
+ host: ip.host,
46
+ port: ip.port
47
+ };
48
+ }
49
+ };
50
+ var ipv6Array = c$5.array(ipv6);
51
+ exports.handshake = {
52
+ preencode(state, m) {
53
+ state.end += 2 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0);
54
+ c$5.buffer.preencode(state, m.noise);
55
+ },
56
+ encode(state, m) {
57
+ const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0);
58
+ c$5.uint.encode(state, flags);
59
+ c$5.uint.encode(state, m.mode);
60
+ c$5.buffer.encode(state, m.noise);
61
+ if (m.peerAddress) ipv4.encode(state, m.peerAddress);
62
+ if (m.relayAddress) ipv4.encode(state, m.relayAddress);
63
+ },
64
+ decode(state) {
65
+ const flags = c$5.uint.decode(state);
66
+ return {
67
+ mode: c$5.uint.decode(state),
68
+ noise: c$5.buffer.decode(state),
69
+ peerAddress: flags & 1 ? ipv4.decode(state) : null,
70
+ relayAddress: flags & 2 ? ipv4.decode(state) : null
71
+ };
72
+ }
73
+ };
74
+ var relayInfoArray = c$5.array({
75
+ preencode(state, m) {
76
+ state.end += 12;
77
+ },
78
+ encode(state, m) {
79
+ ipv4.encode(state, m.relayAddress);
80
+ ipv4.encode(state, m.peerAddress);
81
+ },
82
+ decode(state) {
83
+ return {
84
+ relayAddress: ipv4.decode(state),
85
+ peerAddress: ipv4.decode(state)
86
+ };
87
+ }
88
+ });
89
+ var holepunchInfo = {
90
+ preencode(state, m) {
91
+ c$5.uint.preencode(state, m.id);
92
+ relayInfoArray.preencode(state, m.relays);
93
+ },
94
+ encode(state, m) {
95
+ c$5.uint.encode(state, m.id);
96
+ relayInfoArray.encode(state, m.relays);
97
+ },
98
+ decode(state) {
99
+ return {
100
+ id: c$5.uint.decode(state),
101
+ relays: relayInfoArray.decode(state)
102
+ };
103
+ }
104
+ };
105
+ var udxInfo = {
106
+ preencode(state, m) {
107
+ state.end += 2;
108
+ c$5.uint.preencode(state, m.id);
109
+ c$5.uint.preencode(state, m.seq);
110
+ },
111
+ encode(state, m) {
112
+ c$5.uint.encode(state, 1);
113
+ c$5.uint.encode(state, m.reusableSocket ? 1 : 0);
114
+ c$5.uint.encode(state, m.id);
115
+ c$5.uint.encode(state, m.seq);
116
+ },
117
+ decode(state) {
118
+ return {
119
+ version: c$5.uint.decode(state),
120
+ reusableSocket: (c$5.uint.decode(state) & 1) !== 0,
121
+ id: c$5.uint.decode(state),
122
+ seq: c$5.uint.decode(state)
123
+ };
124
+ }
125
+ };
126
+ var secretStreamInfo = {
127
+ preencode(state, m) {
128
+ c$5.uint.preencode(state, 1);
129
+ },
130
+ encode(state, m) {
131
+ c$5.uint.encode(state, 1);
132
+ },
133
+ decode(state) {
134
+ return { version: c$5.uint.decode(state) };
135
+ }
136
+ };
137
+ var relayThroughInfo = {
138
+ preencode(state, m) {
139
+ c$5.uint.preencode(state, 1);
140
+ c$5.uint.preencode(state, 0);
141
+ c$5.fixed32.preencode(state, m.publicKey);
142
+ c$5.fixed32.preencode(state, m.token);
143
+ },
144
+ encode(state, m) {
145
+ c$5.uint.encode(state, 1);
146
+ c$5.uint.encode(state, 0);
147
+ c$5.fixed32.encode(state, m.publicKey);
148
+ c$5.fixed32.encode(state, m.token);
149
+ },
150
+ decode(state) {
151
+ const version = c$5.uint.decode(state);
152
+ c$5.uint.decode(state);
153
+ return {
154
+ version,
155
+ publicKey: c$5.fixed32.decode(state),
156
+ token: c$5.fixed32.decode(state)
157
+ };
158
+ }
159
+ };
160
+ exports.noisePayload = {
161
+ preencode(state, m) {
162
+ state.end += 4;
163
+ if (m.holepunch) holepunchInfo.preencode(state, m.holepunch);
164
+ if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4);
165
+ if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6);
166
+ if (m.udx) udxInfo.preencode(state, m.udx);
167
+ if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream);
168
+ if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough);
169
+ if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses);
170
+ },
171
+ encode(state, m) {
172
+ let flags = 0;
173
+ if (m.holepunch) flags |= 1;
174
+ if (m.addresses4 && m.addresses4.length) flags |= 2;
175
+ if (m.addresses6 && m.addresses6.length) flags |= 4;
176
+ if (m.udx) flags |= 8;
177
+ if (m.secretStream) flags |= 16;
178
+ if (m.relayThrough) flags |= 32;
179
+ if (m.relayAddresses) flags |= 64;
180
+ c$5.uint.encode(state, 1);
181
+ c$5.uint.encode(state, flags);
182
+ c$5.uint.encode(state, m.error);
183
+ c$5.uint.encode(state, m.firewall);
184
+ if (m.holepunch) holepunchInfo.encode(state, m.holepunch);
185
+ if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4);
186
+ if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6);
187
+ if (m.udx) udxInfo.encode(state, m.udx);
188
+ if (m.secretStream) secretStreamInfo.encode(state, m.secretStream);
189
+ if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough);
190
+ if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses);
191
+ },
192
+ decode(state) {
193
+ const version = c$5.uint.decode(state);
194
+ if (version !== 1) return {
195
+ version,
196
+ error: 0,
197
+ firewall: 0,
198
+ holepunch: null,
199
+ addresses4: [],
200
+ addresses6: [],
201
+ udx: null,
202
+ secretStream: null,
203
+ relayThrough: null,
204
+ relayAddresses: null
205
+ };
206
+ const flags = c$5.uint.decode(state);
207
+ return {
208
+ version,
209
+ error: c$5.uint.decode(state),
210
+ firewall: c$5.uint.decode(state),
211
+ holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
212
+ addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
213
+ addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
214
+ udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
215
+ secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
216
+ relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
217
+ relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
218
+ };
219
+ }
220
+ };
221
+ exports.holepunch = {
222
+ preencode(state, m) {
223
+ state.end += 2;
224
+ c$5.uint.preencode(state, m.id);
225
+ c$5.buffer.preencode(state, m.payload);
226
+ if (m.peerAddress) ipv4.preencode(state, m.peerAddress);
227
+ },
228
+ encode(state, m) {
229
+ const flags = m.peerAddress ? 1 : 0;
230
+ c$5.uint.encode(state, flags);
231
+ c$5.uint.encode(state, m.mode);
232
+ c$5.uint.encode(state, m.id);
233
+ c$5.buffer.encode(state, m.payload);
234
+ if (m.peerAddress) ipv4.encode(state, m.peerAddress);
235
+ },
236
+ decode(state) {
237
+ const flags = c$5.uint.decode(state);
238
+ return {
239
+ mode: c$5.uint.decode(state),
240
+ id: c$5.uint.decode(state),
241
+ payload: c$5.buffer.decode(state),
242
+ peerAddress: flags & 1 ? ipv4.decode(state) : null
243
+ };
244
+ }
245
+ };
246
+ exports.holepunchPayload = {
247
+ preencode(state, m) {
248
+ state.end += 4;
249
+ if (m.addresses) ipv4Array.preencode(state, m.addresses);
250
+ if (m.remoteAddress) state.end += 6;
251
+ if (m.token) state.end += 32;
252
+ if (m.remoteToken) state.end += 32;
253
+ },
254
+ encode(state, m) {
255
+ const flags = (m.connected ? 1 : 0) | (m.punching ? 2 : 0) | (m.addresses ? 4 : 0) | (m.remoteAddress ? 8 : 0) | (m.token ? 16 : 0) | (m.remoteToken ? 32 : 0);
256
+ c$5.uint.encode(state, flags);
257
+ c$5.uint.encode(state, m.error);
258
+ c$5.uint.encode(state, m.firewall);
259
+ c$5.uint.encode(state, m.round);
260
+ if (m.addresses) ipv4Array.encode(state, m.addresses);
261
+ if (m.remoteAddress) ipv4.encode(state, m.remoteAddress);
262
+ if (m.token) c$5.fixed32.encode(state, m.token);
263
+ if (m.remoteToken) c$5.fixed32.encode(state, m.remoteToken);
264
+ },
265
+ decode(state) {
266
+ const flags = c$5.uint.decode(state);
267
+ return {
268
+ error: c$5.uint.decode(state),
269
+ firewall: c$5.uint.decode(state),
270
+ round: c$5.uint.decode(state),
271
+ connected: (flags & 1) !== 0,
272
+ punching: (flags & 2) !== 0,
273
+ addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
274
+ remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
275
+ token: (flags & 16) !== 0 ? c$5.fixed32.decode(state) : null,
276
+ remoteToken: (flags & 32) !== 0 ? c$5.fixed32.decode(state) : null
277
+ };
278
+ }
279
+ };
280
+ var peer = exports.peer = {
281
+ preencode(state, m) {
282
+ state.end += 32;
283
+ ipv4Array.preencode(state, m.relayAddresses);
284
+ },
285
+ encode(state, m) {
286
+ c$5.fixed32.encode(state, m.publicKey);
287
+ ipv4Array.encode(state, m.relayAddresses);
288
+ },
289
+ decode(state) {
290
+ return {
291
+ publicKey: c$5.fixed32.decode(state),
292
+ relayAddresses: ipv4Array.decode(state)
293
+ };
294
+ }
295
+ };
296
+ var peers = exports.peers = c$5.array(peer);
297
+ var rawPeers = c$5.array(c$5.raw);
298
+ exports.lookupRawReply = {
299
+ preencode(state, m) {
300
+ rawPeers.preencode(state, m.peers);
301
+ c$5.uint.preencode(state, m.bump);
302
+ },
303
+ encode(state, m) {
304
+ rawPeers.encode(state, m.peers);
305
+ c$5.uint.encode(state, m.bump);
306
+ },
307
+ decode(state) {
308
+ return {
309
+ peers: peers.decode(state),
310
+ bump: state.start < state.end ? c$5.uint.decode(state) : 0
311
+ };
312
+ }
313
+ };
314
+ exports.announce = {
315
+ preencode(state, m) {
316
+ state.end++;
317
+ if (m.peer) peer.preencode(state, m.peer);
318
+ if (m.refresh) state.end += 32;
319
+ if (m.signature) state.end += 64;
320
+ if (m.bump) c$5.uint.preencode(state, m.bump);
321
+ },
322
+ encode(state, m) {
323
+ const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0);
324
+ c$5.uint.encode(state, flags);
325
+ if (m.peer) peer.encode(state, m.peer);
326
+ if (m.refresh) c$5.fixed32.encode(state, m.refresh);
327
+ if (m.signature) c$5.fixed64.encode(state, m.signature);
328
+ if (m.bump) c$5.uint.encode(state, m.bump);
329
+ },
330
+ decode(state) {
331
+ const flags = c$5.uint.decode(state);
332
+ return {
333
+ peer: (flags & 1) !== 0 ? peer.decode(state) : null,
334
+ refresh: (flags & 2) !== 0 ? c$5.fixed32.decode(state) : null,
335
+ signature: (flags & 4) !== 0 ? c$5.fixed64.decode(state) : null,
336
+ bump: (flags & 8) !== 0 ? c$5.uint.decode(state) : 0
337
+ };
338
+ }
339
+ };
340
+ exports.mutableSignable = {
341
+ preencode(state, m) {
342
+ c$5.uint.preencode(state, m.seq);
343
+ c$5.buffer.preencode(state, m.value);
344
+ },
345
+ encode(state, m) {
346
+ c$5.uint.encode(state, m.seq);
347
+ c$5.buffer.encode(state, m.value);
348
+ },
349
+ decode(state) {
350
+ return {
351
+ seq: c$5.uint.decode(state),
352
+ value: c$5.buffer.decode(state)
353
+ };
354
+ }
355
+ };
356
+ exports.mutablePutRequest = {
357
+ preencode(state, m) {
358
+ c$5.fixed32.preencode(state, m.publicKey);
359
+ c$5.uint.preencode(state, m.seq);
360
+ c$5.buffer.preencode(state, m.value);
361
+ c$5.fixed64.preencode(state, m.signature);
362
+ },
363
+ encode(state, m) {
364
+ c$5.fixed32.encode(state, m.publicKey);
365
+ c$5.uint.encode(state, m.seq);
366
+ c$5.buffer.encode(state, m.value);
367
+ c$5.fixed64.encode(state, m.signature);
368
+ },
369
+ decode(state) {
370
+ return {
371
+ publicKey: c$5.fixed32.decode(state),
372
+ seq: c$5.uint.decode(state),
373
+ value: c$5.buffer.decode(state),
374
+ signature: c$5.fixed64.decode(state)
375
+ };
376
+ }
377
+ };
378
+ exports.mutableGetResponse = {
379
+ preencode(state, m) {
380
+ c$5.uint.preencode(state, m.seq);
381
+ c$5.buffer.preencode(state, m.value);
382
+ c$5.fixed64.preencode(state, m.signature);
383
+ },
384
+ encode(state, m) {
385
+ c$5.uint.encode(state, m.seq);
386
+ c$5.buffer.encode(state, m.value);
387
+ c$5.fixed64.encode(state, m.signature);
388
+ },
389
+ decode(state) {
390
+ return {
391
+ seq: c$5.uint.decode(state),
392
+ value: c$5.buffer.decode(state),
393
+ signature: c$5.fixed64.decode(state)
394
+ };
395
+ }
396
+ };
397
+ exports.pluginRequest = {
398
+ preencode(state, m) {
399
+ c$5.string.preencode(state, m.plugin);
400
+ c$5.uint.preencode(state, m.version);
401
+ c$5.uint.preencode(state, m.command);
402
+ state.end++;
403
+ if (m.value) c$5.buffer.preencode(state, m.value);
404
+ },
405
+ encode(state, m) {
406
+ const flags = m.value ? 1 : 0;
407
+ c$5.string.encode(state, m.plugin);
408
+ c$5.uint.encode(state, m.version);
409
+ c$5.uint.encode(state, m.command);
410
+ c$5.uint.encode(state, flags);
411
+ if (m.value) c$5.buffer.encode(state, m.value);
412
+ },
413
+ decode(state) {
414
+ return {
415
+ plugin: c$5.string.decode(state),
416
+ version: c$5.uint.decode(state),
417
+ command: c$5.uint.decode(state),
418
+ value: (c$5.uint.decode(state) & 1) !== 0 ? c$5.buffer.decode(state) : null
419
+ };
420
+ }
421
+ };
422
+ }));
423
+ //#endregion
424
+ //#region ../../node_modules/hyperdht/lib/socket-pool.js
425
+ var require_socket_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => {
426
+ var b4a$18 = __require("b4a");
427
+ var LINGER_TIME = 3e3;
428
+ module.exports = class SocketPool {
429
+ constructor(dht, host) {
430
+ this._dht = dht;
431
+ this._sockets = /* @__PURE__ */ new Map();
432
+ this._lingering = /* @__PURE__ */ new Set();
433
+ this._host = host;
434
+ this.routes = new SocketRoutes(this);
435
+ this.stats = {
436
+ socketsAdded: 0,
437
+ socketsRemoved: 0
438
+ };
439
+ }
440
+ _onmessage(ref, data, address) {
441
+ this._dht.onmessage(ref.socket, data, address);
442
+ }
443
+ _add(ref) {
444
+ this._sockets.set(ref.socket, ref);
445
+ this.stats.socketsAdded++;
446
+ }
447
+ _remove(ref) {
448
+ const removed = this._sockets.delete(ref.socket);
449
+ this._lingering.delete(ref);
450
+ if (removed) this.stats.socketsRemoved++;
451
+ }
452
+ lookup(socket) {
453
+ return this._sockets.get(socket) || null;
454
+ }
455
+ setReusable(socket, bool) {
456
+ const ref = this.lookup(socket);
457
+ if (ref) ref.reusable = bool;
458
+ }
459
+ acquire() {
460
+ return new SocketRef(this);
461
+ }
462
+ async destroy() {
463
+ const closing = [];
464
+ for (const ref of this._sockets.values()) {
465
+ ref._unlinger();
466
+ closing.push(ref.socket.close());
467
+ }
468
+ await Promise.allSettled(closing);
469
+ }
470
+ };
471
+ var SocketRoutes = class {
472
+ constructor(pool) {
473
+ this._pool = pool;
474
+ this._routes = /* @__PURE__ */ new Map();
475
+ }
476
+ add(publicKey, rawStream) {
477
+ if (rawStream.socket) this._onconnect(publicKey, rawStream);
478
+ else rawStream.on("connect", this._onconnect.bind(this, publicKey, rawStream));
479
+ }
480
+ get(publicKey) {
481
+ const id = b4a$18.toString(publicKey, "hex");
482
+ const route = this._routes.get(id);
483
+ if (!route) return null;
484
+ return route;
485
+ }
486
+ _onconnect(publicKey, rawStream) {
487
+ const id = b4a$18.toString(publicKey, "hex");
488
+ const socket = rawStream.socket;
489
+ let route = this._routes.get(id);
490
+ if (!route) {
491
+ const gc = () => {
492
+ if (this._routes.get(id) === route) this._routes.delete(id);
493
+ socket.removeListener("close", gc);
494
+ };
495
+ route = {
496
+ socket,
497
+ address: {
498
+ host: rawStream.remoteHost,
499
+ port: rawStream.remotePort
500
+ },
501
+ gc
502
+ };
503
+ this._routes.set(id, route);
504
+ socket.on("close", gc);
505
+ }
506
+ this._pool.setReusable(socket, true);
507
+ rawStream.on("error", () => {
508
+ this._pool.setReusable(socket, false);
509
+ if (!route) route = this._routes.get(id);
510
+ if (route && route.socket === socket) route.gc();
511
+ });
512
+ }
513
+ };
514
+ var SocketRef = class {
515
+ constructor(pool) {
516
+ this._pool = pool;
517
+ this.onholepunchmessage = noop;
518
+ this.reusable = false;
519
+ this.socket = pool._dht.udx.createSocket();
520
+ this.socket.on("close", this._onclose.bind(this)).on("message", this._onmessage.bind(this)).on("idle", this._onidle.bind(this)).on("busy", this._onbusy.bind(this)).bind(0, this._pool._host);
521
+ this._refs = 1;
522
+ this._released = false;
523
+ this._closed = false;
524
+ this._timeout = null;
525
+ this._wasBusy = false;
526
+ this._pool._add(this);
527
+ }
528
+ _onclose() {
529
+ this._pool._remove(this);
530
+ }
531
+ _onmessage(data, address) {
532
+ if (data.byteLength > 1) this._pool._onmessage(this, data, address);
533
+ else this.onholepunchmessage(data, address, this);
534
+ }
535
+ _onidle() {
536
+ this._closeMaybe();
537
+ }
538
+ _onbusy() {
539
+ this._wasBusy = true;
540
+ this._unlinger();
541
+ }
542
+ _reset() {
543
+ this.onholepunchmessage = noop;
544
+ }
545
+ _closeMaybe() {
546
+ if (this._refs === 0 && this.socket.idle && !this._timeout) this._close();
547
+ }
548
+ _lingeringClose() {
549
+ this._pool._lingering.delete(this);
550
+ this._timeout = null;
551
+ this._closeMaybe();
552
+ }
553
+ _close() {
554
+ this._unlinger();
555
+ if (this.reusable && this._wasBusy) {
556
+ this._wasBusy = false;
557
+ this._pool._lingering.add(this);
558
+ this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME);
559
+ return;
560
+ }
561
+ this._closed = true;
562
+ this.socket.close();
563
+ }
564
+ _unlinger() {
565
+ if (this._timeout !== null) {
566
+ clearTimeout(this._timeout);
567
+ this._pool._lingering.delete(this);
568
+ this._timeout = null;
569
+ }
570
+ }
571
+ get free() {
572
+ return this._refs === 0;
573
+ }
574
+ active() {
575
+ this._refs++;
576
+ this._unlinger();
577
+ }
578
+ inactive() {
579
+ this._refs--;
580
+ this._closeMaybe();
581
+ }
582
+ address() {
583
+ return this.socket.address();
584
+ }
585
+ release() {
586
+ if (this._released) return;
587
+ this._released = true;
588
+ this._reset();
589
+ this._refs--;
590
+ this._closeMaybe();
591
+ }
592
+ };
593
+ function noop() {}
594
+ }));
595
+ //#endregion
596
+ //#region ../../node_modules/hyperdht/lib/encode.js
597
+ var require_encode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
598
+ var b4a$17 = __require("b4a");
599
+ var cenc = __require("compact-encoding");
600
+ function encodeUnslab(enc, m) {
601
+ const state = cenc.state();
602
+ enc.preencode(state, m);
603
+ state.buffer = b4a$17.allocUnsafeSlow(state.end);
604
+ enc.encode(state, m);
605
+ return state.buffer;
606
+ }
607
+ module.exports = { encodeUnslab };
608
+ }));
609
+ //#endregion
610
+ //#region ../../node_modules/hyperdht/lib/constants.js
611
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports) => {
612
+ var crypto = __require("hypercore-crypto");
613
+ var COMMANDS = exports.COMMANDS = {
614
+ PEER_HANDSHAKE: 0,
615
+ PEER_HOLEPUNCH: 1,
616
+ FIND_PEER: 2,
617
+ LOOKUP: 3,
618
+ ANNOUNCE: 4,
619
+ UNANNOUNCE: 5,
620
+ MUTABLE_PUT: 6,
621
+ MUTABLE_GET: 7,
622
+ IMMUTABLE_PUT: 8,
623
+ IMMUTABLE_GET: 9,
624
+ PLUGIN: 10
625
+ };
626
+ exports.BOOTSTRAP_NODES = [
627
+ "88.99.3.86@node1.hyperdht.org:49737",
628
+ "142.93.90.113@node2.hyperdht.org:49737",
629
+ "138.68.147.8@node3.hyperdht.org:49737"
630
+ ];
631
+ exports.FIREWALL = {
632
+ UNKNOWN: 0,
633
+ OPEN: 1,
634
+ CONSISTENT: 2,
635
+ RANDOM: 3
636
+ };
637
+ exports.ERROR = {
638
+ NONE: 0,
639
+ ABORTED: 1,
640
+ VERSION_MISMATCH: 2,
641
+ TRY_LATER: 3,
642
+ SEQ_REUSED: 16,
643
+ SEQ_TOO_LOW: 17
644
+ };
645
+ var [NS_ANNOUNCE, NS_UNANNOUNCE, NS_MUTABLE_PUT, NS_PEER_HANDSHAKE, NS_PEER_HOLEPUNCH, NS_PLUGIN] = crypto.namespace("hyperswarm/dht", [
646
+ COMMANDS.ANNOUNCE,
647
+ COMMANDS.UNANNOUNCE,
648
+ COMMANDS.MUTABLE_PUT,
649
+ COMMANDS.PEER_HANDSHAKE,
650
+ COMMANDS.PEER_HOLEPUNCH,
651
+ COMMANDS.PLUGIN
652
+ ]);
653
+ exports.NS = {
654
+ ANNOUNCE: NS_ANNOUNCE,
655
+ UNANNOUNCE: NS_UNANNOUNCE,
656
+ MUTABLE_PUT: NS_MUTABLE_PUT,
657
+ PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
658
+ PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
659
+ PLUGIN: NS_PLUGIN
660
+ };
661
+ }));
662
+ //#endregion
663
+ //#region ../../node_modules/hyperdht/lib/persistent.js
664
+ var require_persistent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
665
+ var c$4 = __require("compact-encoding");
666
+ var sodium$6 = __require("sodium-universal");
667
+ var RecordCache = __require("record-cache");
668
+ var Cache$2 = __require("xache");
669
+ var b4a$16 = __require("b4a");
670
+ var unslab$1 = __require("unslab");
671
+ var { encodeUnslab } = require_encode();
672
+ var m = require_messages();
673
+ var { NS, ERROR } = require_constants();
674
+ var EMPTY = b4a$16.alloc(0);
675
+ var TMP = b4a$16.allocUnsafe(32);
676
+ var MAX_BUMP_DRIFT = 6e4;
677
+ module.exports = class Persistent {
678
+ constructor(dht, opts) {
679
+ this.dht = dht;
680
+ this.records = new RecordCache(opts.records);
681
+ this.bumps = new Cache$2(opts.bumps);
682
+ this.refreshes = new Cache$2(opts.refreshes);
683
+ this.mutables = new Cache$2(opts.mutables);
684
+ this.immutables = new Cache$2(opts.immutables);
685
+ }
686
+ onlookup(req) {
687
+ if (!req.target) return;
688
+ const k = b4a$16.toString(req.target, "hex");
689
+ const records = this.records.get(k, 20);
690
+ const bump = this.bumps.get(k) || 0;
691
+ const fwd = this.dht._router.get(k);
692
+ if (fwd && records.length < 20) records.push(fwd.record);
693
+ req.reply(records.length ? c$4.encode(m.lookupRawReply, {
694
+ peers: records,
695
+ bump
696
+ }) : null);
697
+ }
698
+ onfindpeer(req) {
699
+ if (!req.target) return;
700
+ const fwd = this.dht._router.get(req.target);
701
+ req.reply(fwd ? fwd.record : null);
702
+ }
703
+ unannounce(target, publicKey) {
704
+ const k = b4a$16.toString(target, "hex");
705
+ sodium$6.crypto_generichash(TMP, publicKey);
706
+ if (b4a$16.equals(TMP, target)) this.dht._router.delete(k);
707
+ this.records.remove(k, publicKey);
708
+ }
709
+ onunannounce(req) {
710
+ if (!req.target || !req.token) return;
711
+ const unann = decode(m.announce, req.value);
712
+ if (unann === null) return;
713
+ const { peer, signature } = unann;
714
+ if (!peer || !signature) return;
715
+ const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE);
716
+ if (!sodium$6.crypto_sign_verify_detached(signature, signable, peer.publicKey)) return;
717
+ this.unannounce(req.target, peer.publicKey);
718
+ req.reply(null, {
719
+ token: false,
720
+ closerNodes: false
721
+ });
722
+ }
723
+ _onrefresh(token, req) {
724
+ sodium$6.crypto_generichash(TMP, token);
725
+ const activeRefresh = b4a$16.toString(TMP, "hex");
726
+ const r = this.refreshes.get(activeRefresh);
727
+ if (!r) return;
728
+ const { announceSelf, k, record } = r;
729
+ const publicKey = record.subarray(0, 32);
730
+ if (announceSelf) {
731
+ this.dht._router.set(k, {
732
+ relay: req.from,
733
+ record,
734
+ onconnect: null,
735
+ onholepunch: null
736
+ });
737
+ this.records.remove(k, publicKey);
738
+ } else this.records.add(k, publicKey, record);
739
+ this.refreshes.delete(activeRefresh);
740
+ this.refreshes.set(b4a$16.toString(token, "hex"), r);
741
+ req.reply(null, {
742
+ token: false,
743
+ closerNodes: false
744
+ });
745
+ }
746
+ onannounce(req) {
747
+ if (!req.target || !req.token || !this.dht.id) return;
748
+ const ann = decode(m.announce, req.value);
749
+ if (ann === null) return;
750
+ const { peer, refresh, signature, bump } = ann;
751
+ if (!peer) {
752
+ if (!refresh) return;
753
+ this._onrefresh(refresh, req);
754
+ return;
755
+ }
756
+ const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE);
757
+ if (!signature || !sodium$6.crypto_sign_verify_detached(signature, signable, peer.publicKey)) return;
758
+ if (peer.relayAddresses.length > 3) peer.relayAddresses = peer.relayAddresses.slice(0, 3);
759
+ sodium$6.crypto_generichash(TMP, peer.publicKey);
760
+ const k = b4a$16.toString(req.target, "hex");
761
+ const announceSelf = b4a$16.equals(TMP, req.target);
762
+ const record = encodeUnslab(m.peer, peer);
763
+ if (announceSelf) {
764
+ this.dht._router.set(k, {
765
+ relay: req.from,
766
+ record,
767
+ onconnect: null,
768
+ onholepunch: null
769
+ });
770
+ this.records.remove(k, peer.publicKey);
771
+ } else {
772
+ if (bump > (this.bumps.get(k) || 0) && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump);
773
+ this.records.add(k, peer.publicKey, record);
774
+ }
775
+ if (refresh) this.refreshes.set(b4a$16.toString(refresh, "hex"), {
776
+ k,
777
+ record,
778
+ announceSelf
779
+ });
780
+ req.reply(null, {
781
+ token: false,
782
+ closerNodes: false
783
+ });
784
+ }
785
+ onmutableget(req) {
786
+ if (!req.target || !req.value) return;
787
+ let seq = 0;
788
+ try {
789
+ seq = c$4.decode(c$4.uint, req.value);
790
+ } catch {
791
+ return;
792
+ }
793
+ const k = b4a$16.toString(req.target, "hex");
794
+ const value = this.mutables.get(k);
795
+ if (!value) {
796
+ req.reply(null);
797
+ return;
798
+ }
799
+ const localSeq = c$4.decode(c$4.uint, value);
800
+ req.reply(localSeq < seq ? null : value);
801
+ }
802
+ onmutableput(req) {
803
+ if (!req.target || !req.token || !req.value) return;
804
+ const p = decode(m.mutablePutRequest, req.value);
805
+ if (!p) return;
806
+ const { publicKey, seq, value, signature } = p;
807
+ const hash = b4a$16.allocUnsafe(32);
808
+ sodium$6.crypto_generichash(hash, publicKey);
809
+ if (!b4a$16.equals(hash, req.target)) return;
810
+ if (!value || !verifyMutable(signature, seq, value, publicKey)) return;
811
+ const k = b4a$16.toString(hash, "hex");
812
+ const local = this.mutables.get(k);
813
+ if (local) {
814
+ const existing = c$4.decode(m.mutableGetResponse, local);
815
+ if (existing.value && existing.seq === seq && b4a$16.compare(value, existing.value) !== 0) {
816
+ req.error(ERROR.SEQ_REUSED);
817
+ return;
818
+ }
819
+ if (seq < existing.seq) {
820
+ req.error(ERROR.SEQ_TOO_LOW);
821
+ return;
822
+ }
823
+ }
824
+ this.mutables.set(k, encodeUnslab(m.mutableGetResponse, {
825
+ seq,
826
+ value,
827
+ signature
828
+ }));
829
+ req.reply(null);
830
+ }
831
+ onimmutableget(req) {
832
+ if (!req.target) return;
833
+ const k = b4a$16.toString(req.target, "hex");
834
+ const value = this.immutables.get(k);
835
+ req.reply(value || null);
836
+ }
837
+ onimmutableput(req) {
838
+ if (!req.target || !req.token || !req.value) return;
839
+ const hash = b4a$16.alloc(32);
840
+ sodium$6.crypto_generichash(hash, req.value);
841
+ if (!b4a$16.equals(hash, req.target)) return;
842
+ const k = b4a$16.toString(hash, "hex");
843
+ this.immutables.set(k, unslab$1(req.value));
844
+ req.reply(null);
845
+ }
846
+ onplugin(req) {
847
+ if (!req.value) return;
848
+ const plugreq = decode(m.pluginRequest, req.value);
849
+ if (plugreq === null) return;
850
+ const p = this.dht.plugins.get(plugreq.plugin);
851
+ if (!p || p.version !== plugreq.version) return;
852
+ p.onrequest(plugreq, req);
853
+ }
854
+ destroy() {
855
+ this.records.destroy();
856
+ this.refreshes.destroy();
857
+ this.mutables.destroy();
858
+ this.immutables.destroy();
859
+ }
860
+ static signMutable(seq, value, keyPair) {
861
+ const signable = b4a$16.allocUnsafe(64);
862
+ const hash = signable.subarray(32);
863
+ signable.set(NS.MUTABLE_PUT, 0);
864
+ sodium$6.crypto_generichash(hash, c$4.encode(m.mutableSignable, {
865
+ seq,
866
+ value
867
+ }));
868
+ return sign(signable, keyPair);
869
+ }
870
+ static verifyMutable(signature, seq, value, publicKey) {
871
+ return verifyMutable(signature, seq, value, publicKey);
872
+ }
873
+ static signAnnounce(target, token, id, ann, keyPair) {
874
+ return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair);
875
+ }
876
+ static signUnannounce(target, token, id, ann, keyPair) {
877
+ return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair);
878
+ }
879
+ };
880
+ function verifyMutable(signature, seq, value, publicKey) {
881
+ const signable = b4a$16.allocUnsafe(64);
882
+ const hash = signable.subarray(32);
883
+ signable.set(NS.MUTABLE_PUT, 0);
884
+ sodium$6.crypto_generichash(hash, c$4.encode(m.mutableSignable, {
885
+ seq,
886
+ value
887
+ }));
888
+ return sodium$6.crypto_sign_verify_detached(signature, signable, publicKey);
889
+ }
890
+ function annSignable(target, token, id, ann, ns) {
891
+ const signable = b4a$16.allocUnsafe(64);
892
+ const hash = signable.subarray(32);
893
+ signable.set(ns, 0);
894
+ sodium$6.crypto_generichash_batch(hash, [
895
+ target,
896
+ id,
897
+ token,
898
+ c$4.encode(m.peer, ann.peer),
899
+ ann.refresh || EMPTY
900
+ ]);
901
+ return signable;
902
+ }
903
+ function sign(signable, keyPair) {
904
+ if (keyPair.sign) return keyPair.sign(signable);
905
+ const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair;
906
+ const signature = b4a$16.allocUnsafe(64);
907
+ sodium$6.crypto_sign_detached(signature, signable, secretKey);
908
+ return signature;
909
+ }
910
+ function decode(enc, val) {
911
+ try {
912
+ return val && c$4.decode(enc, val);
913
+ } catch (err) {
914
+ return null;
915
+ }
916
+ }
917
+ }));
918
+ //#endregion
919
+ //#region ../../node_modules/hyperdht/lib/errors.js
920
+ var require_errors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
921
+ module.exports = class DHTError extends Error {
922
+ constructor(msg, code, fn = DHTError) {
923
+ super(`${code}: ${msg}`);
924
+ this.code = code;
925
+ if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
926
+ }
927
+ get name() {
928
+ return "DHTError";
929
+ }
930
+ static BAD_HANDSHAKE_REPLY(msg = "Bad handshake reply") {
931
+ return new DHTError(msg, "BAD_HANDSHAKE_REPLY", DHTError.BAD_HANDSHAKE_REPLY);
932
+ }
933
+ static BAD_HOLEPUNCH_REPLY(msg = "Bad holepunch reply") {
934
+ return new DHTError(msg, "BAD_HOLEPUNCH_REPLY", DHTError.BAD_HOLEPUNCH_REPLY);
935
+ }
936
+ static HOLEPUNCH_ABORTED(msg = "Holepunch aborted") {
937
+ return new DHTError(msg, "HOLEPUNCH_ABORTED", DHTError.HOLEPUNCH_ABORTED);
938
+ }
939
+ static HOLEPUNCH_INVALID(msg = "Invalid holepunch payload") {
940
+ return new DHTError(msg, "HOLEPUNCH_INVALID", DHTError.HOLEPUNCH_INVALID);
941
+ }
942
+ static HOLEPUNCH_PROBE_TIMEOUT(msg = "Holepunching probe did not finish in time") {
943
+ return new DHTError(msg, "HOLEPUNCH_PROBE_TIMEOUT", DHTError.HOLEPUNCH_PROBE_TIMEOUT);
944
+ }
945
+ static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = "Both remote and local NATs are randomized") {
946
+ return new DHTError(msg, "HOLEPUNCH_DOUBLE_RANDOMIZED_NATS", DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS);
947
+ }
948
+ static CANNOT_HOLEPUNCH(msg = "Cannot holepunch to remote") {
949
+ return new DHTError(msg, "CANNOT_HOLEPUNCH", DHTError.CANNOT_HOLEPUNCH);
950
+ }
951
+ static REMOTE_NOT_HOLEPUNCHING(msg = "Remote is not holepunching") {
952
+ return new DHTError(msg, "REMOTE_NOT_HOLEPUNCHING", DHTError.REMOTE_NOT_HOLEPUNCHING);
953
+ }
954
+ static REMOTE_NOT_HOLEPUNCHABLE(msg = "Remote is not holepunchable") {
955
+ return new DHTError(msg, "REMOTE_NOT_HOLEPUNCHABLE", DHTError.REMOTE_NOT_HOLEPUNCHABLE);
956
+ }
957
+ static REMOTE_ABORTED(msg = "Remote aborted") {
958
+ return new DHTError(msg, "REMOTE_ABORTED", DHTError.REMOTE_ABORTED);
959
+ }
960
+ static HANDSHAKE_UNFINISHED(msg = "Handshake did not finish") {
961
+ return new DHTError(msg, "HANDSHAKE_UNFINISHED", DHTError.HANDSHAKE_UNFINISHED);
962
+ }
963
+ static HANDSHAKE_INVALID(msg = "Received invalid handshake") {
964
+ return new DHTError(msg, "HANDSHAKE_INVALID", DHTError.HANDSHAKE_INVALID);
965
+ }
966
+ static ALREADY_LISTENING(msg = "Already listening") {
967
+ return new DHTError(msg, "ALREADY_LISTENING", DHTError.ALREADY_LISTENING);
968
+ }
969
+ static KEYPAIR_ALREADY_USED(msg = "Keypair already used") {
970
+ return new DHTError(msg, "KEYPAIR_ALREADY_USED", DHTError.KEYPAIR_ALREADY_USED);
971
+ }
972
+ static NODE_DESTROYED(msg = "Node destroyed") {
973
+ return new DHTError(msg, "NODE_DESTROYED", DHTError.NODE_DESTROYED);
974
+ }
975
+ static PEER_CONNECTION_FAILED(msg = "Could not connect to peer") {
976
+ return new DHTError(msg, "PEER_CONNECTION_FAILED", DHTError.PEER_CONNECTION_FAILED);
977
+ }
978
+ static PEER_NOT_FOUND(msg = "Peer not found") {
979
+ return new DHTError(msg, "PEER_NOT_FOUND", DHTError.PEER_NOT_FOUND);
980
+ }
981
+ static STREAM_NOT_CONNECTED(msg = "Stream is not connected") {
982
+ return new DHTError(msg, "STREAM_NOT_CONNECTED", DHTError.STREAM_NOT_CONNECTED);
983
+ }
984
+ static SERVER_INCOMPATIBLE(msg = "Server is using an incompatible version") {
985
+ return new DHTError(msg, "SERVER_INCOMPATIBLE", DHTError.SERVER_INCOMPATIBLE);
986
+ }
987
+ static SERVER_ERROR(msg = "Server returned an error") {
988
+ return new DHTError(msg, "SERVER_ERROR", DHTError.SERVER_ERROR);
989
+ }
990
+ static DUPLICATE_CONNECTION(msg = "Duplicate connection") {
991
+ return new DHTError(msg, "DUPLICATE_CONNECTION", DHTError.DUPLICATE_CONNECTION);
992
+ }
993
+ static RELAY_ABORTED(msg = "Relay aborted") {
994
+ return new DHTError(msg, "RELAY_ABORTED", DHTError.RELAY_ABORTED);
995
+ }
996
+ static SUSPENDED(msg = "Suspended") {
997
+ return new DHTError(msg, "SUSPENDED", DHTError.SUSPENDED);
998
+ }
999
+ };
1000
+ }));
1001
+ //#endregion
1002
+ //#region ../../node_modules/hyperdht/lib/router.js
1003
+ var require_router = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1004
+ var c$3 = __require("compact-encoding");
1005
+ var Cache$1 = __require("xache");
1006
+ var safetyCatch$5 = __require("safety-catch");
1007
+ var b4a$15 = __require("b4a");
1008
+ var { handshake, holepunch } = require_messages();
1009
+ var { COMMANDS } = require_constants();
1010
+ var { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require_errors();
1011
+ var FROM_CLIENT = 0;
1012
+ var FROM_SERVER = 1;
1013
+ var FROM_RELAY = 2;
1014
+ var FROM_SECOND_RELAY = 3;
1015
+ var REPLY = 4;
1016
+ module.exports = class Router {
1017
+ constructor(dht, opts) {
1018
+ this.dht = dht;
1019
+ this.forwards = new Cache$1(opts.forwards);
1020
+ }
1021
+ set(target, state) {
1022
+ if (state.onpeerhandshake) this.forwards.retain(toString(target), state);
1023
+ else this.forwards.set(toString(target), state);
1024
+ }
1025
+ get(target) {
1026
+ return this.forwards.get(toString(target));
1027
+ }
1028
+ delete(target) {
1029
+ this.forwards.delete(toString(target));
1030
+ }
1031
+ destroy() {
1032
+ this.forwards.destroy();
1033
+ }
1034
+ async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
1035
+ const dht = this.dht;
1036
+ const requestValue = c$3.encode(handshake, {
1037
+ mode: FROM_CLIENT,
1038
+ noise,
1039
+ peerAddress,
1040
+ relayAddress
1041
+ });
1042
+ const res = await dht.request({
1043
+ command: COMMANDS.PEER_HANDSHAKE,
1044
+ target,
1045
+ value: requestValue
1046
+ }, to, {
1047
+ socket,
1048
+ session
1049
+ });
1050
+ const hs = decode(handshake, res.value);
1051
+ if (!hs || hs.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port || !hs.noise) throw BAD_HANDSHAKE_REPLY();
1052
+ return {
1053
+ noise: hs.noise,
1054
+ relayed: !!hs.peerAddress,
1055
+ serverAddress: hs.peerAddress || to,
1056
+ clientAddress: res.to
1057
+ };
1058
+ }
1059
+ async onpeerhandshake(req) {
1060
+ const hs = req.value && decode(handshake, req.value);
1061
+ if (!hs) return;
1062
+ const { mode, noise, peerAddress, relayAddress } = hs;
1063
+ const state = req.target && this.get(req.target);
1064
+ const isServer = !!(state && state.onpeerhandshake);
1065
+ const relay = state && state.relay;
1066
+ if (isServer) {
1067
+ let reply = null;
1068
+ try {
1069
+ reply = noise && await state.onpeerhandshake({
1070
+ noise,
1071
+ peerAddress
1072
+ }, req);
1073
+ } catch (e) {
1074
+ safetyCatch$5(e);
1075
+ return;
1076
+ }
1077
+ if (!reply || !reply.noise) return;
1078
+ const opts = {
1079
+ socket: reply.socket,
1080
+ closerNodes: false,
1081
+ token: false
1082
+ };
1083
+ switch (mode) {
1084
+ case FROM_CLIENT:
1085
+ req.reply(c$3.encode(handshake, {
1086
+ mode: REPLY,
1087
+ noise: reply.noise,
1088
+ peerAddress: null
1089
+ }), opts);
1090
+ return;
1091
+ case FROM_RELAY:
1092
+ req.relay(c$3.encode(handshake, {
1093
+ mode: FROM_SERVER,
1094
+ noise: reply.noise,
1095
+ peerAddress
1096
+ }), req.from, opts);
1097
+ return;
1098
+ case FROM_SECOND_RELAY:
1099
+ if (!relayAddress) return;
1100
+ req.relay(c$3.encode(handshake, {
1101
+ mode: FROM_SERVER,
1102
+ noise: reply.noise,
1103
+ peerAddress
1104
+ }), relayAddress, opts);
1105
+ return;
1106
+ }
1107
+ } else switch (mode) {
1108
+ case FROM_CLIENT:
1109
+ if (!noise) return;
1110
+ if (!relay && !relayAddress) {
1111
+ req.reply(null, {
1112
+ token: false,
1113
+ closerNodes: true
1114
+ });
1115
+ return;
1116
+ }
1117
+ req.relay(c$3.encode(handshake, {
1118
+ mode: FROM_RELAY,
1119
+ noise,
1120
+ peerAddress: req.from,
1121
+ relayAddress: null
1122
+ }), relayAddress || relay);
1123
+ return;
1124
+ case FROM_RELAY:
1125
+ if (!relay || !noise) return;
1126
+ req.relay(c$3.encode(handshake, {
1127
+ mode: FROM_SECOND_RELAY,
1128
+ noise,
1129
+ peerAddress,
1130
+ relayAddress: req.from
1131
+ }), relay);
1132
+ return;
1133
+ case FROM_SERVER:
1134
+ if (!peerAddress || !noise) return;
1135
+ req.reply(c$3.encode(handshake, {
1136
+ mode: REPLY,
1137
+ noise,
1138
+ peerAddress: req.from,
1139
+ relayAddress: null
1140
+ }), {
1141
+ to: peerAddress,
1142
+ closerNodes: false,
1143
+ token: false
1144
+ });
1145
+ return;
1146
+ }
1147
+ }
1148
+ async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
1149
+ const dht = this.dht;
1150
+ const requestValue = c$3.encode(holepunch, {
1151
+ mode: FROM_CLIENT,
1152
+ id,
1153
+ payload,
1154
+ peerAddress
1155
+ });
1156
+ const res = await dht.request({
1157
+ command: COMMANDS.PEER_HOLEPUNCH,
1158
+ target,
1159
+ value: requestValue
1160
+ }, to, {
1161
+ socket,
1162
+ session
1163
+ });
1164
+ const hp = decode(holepunch, res.value);
1165
+ if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) throw BAD_HOLEPUNCH_REPLY();
1166
+ return {
1167
+ from: res.from,
1168
+ to: res.to,
1169
+ payload: hp.payload,
1170
+ peerAddress: hp.peerAddress || to
1171
+ };
1172
+ }
1173
+ async onpeerholepunch(req) {
1174
+ const hp = req.value && decode(holepunch, req.value);
1175
+ if (!hp) return;
1176
+ const { mode, id, payload, peerAddress } = hp;
1177
+ const state = req.target && this.get(req.target);
1178
+ const isServer = !!(state && state.onpeerholepunch);
1179
+ const relay = state && state.relay;
1180
+ switch (mode) {
1181
+ case FROM_CLIENT:
1182
+ if (!peerAddress && !relay) return;
1183
+ req.relay(c$3.encode(holepunch, {
1184
+ mode: FROM_RELAY,
1185
+ id,
1186
+ payload,
1187
+ peerAddress: req.from
1188
+ }), peerAddress || relay);
1189
+ return;
1190
+ case FROM_RELAY: {
1191
+ if (!isServer || !peerAddress) return;
1192
+ let reply = null;
1193
+ try {
1194
+ reply = await state.onpeerholepunch({
1195
+ id,
1196
+ payload,
1197
+ peerAddress
1198
+ }, req);
1199
+ } catch (e) {
1200
+ safetyCatch$5(e);
1201
+ return;
1202
+ }
1203
+ if (!reply) return;
1204
+ const opts = {
1205
+ socket: reply.socket,
1206
+ closerNodes: false,
1207
+ token: false
1208
+ };
1209
+ req.relay(c$3.encode(holepunch, {
1210
+ mode: FROM_SERVER,
1211
+ id: 0,
1212
+ payload: reply.payload,
1213
+ peerAddress
1214
+ }), req.from, opts);
1215
+ return;
1216
+ }
1217
+ case FROM_SERVER:
1218
+ req.reply(c$3.encode(holepunch, {
1219
+ mode: REPLY,
1220
+ id,
1221
+ payload,
1222
+ peerAddress: req.from
1223
+ }), {
1224
+ to: peerAddress,
1225
+ closerNodes: false,
1226
+ token: false
1227
+ });
1228
+ return;
1229
+ }
1230
+ }
1231
+ };
1232
+ function decode(enc, val) {
1233
+ try {
1234
+ return c$3.decode(enc, val);
1235
+ } catch {
1236
+ return null;
1237
+ }
1238
+ }
1239
+ function toString(t) {
1240
+ return typeof t === "string" ? t : b4a$15.toString(t, "hex");
1241
+ }
1242
+ }));
1243
+ //#endregion
1244
+ //#region ../../node_modules/hyperdht/node_modules/noise-handshake/cipher.js
1245
+ var require_cipher = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1246
+ var sodium$5 = __require("sodium-universal");
1247
+ var b4a$14 = __require("b4a");
1248
+ module.exports = class CipherState {
1249
+ constructor(key) {
1250
+ this.key = key || null;
1251
+ this.nonce = 0;
1252
+ this.CIPHER_ALG = "ChaChaPoly";
1253
+ }
1254
+ initialiseKey(key) {
1255
+ this.key = key;
1256
+ this.nonce = 0;
1257
+ }
1258
+ setNonce(nonce) {
1259
+ this.nonce = nonce;
1260
+ }
1261
+ encrypt(plaintext, ad) {
1262
+ if (!this.hasKey) return plaintext;
1263
+ if (!ad) ad = b4a$14.alloc(0);
1264
+ const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext);
1265
+ if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`);
1266
+ this.nonce++;
1267
+ return ciphertext;
1268
+ }
1269
+ decrypt(ciphertext, ad) {
1270
+ if (!this.hasKey) return ciphertext;
1271
+ if (!ad) ad = b4a$14.alloc(0);
1272
+ if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`);
1273
+ const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext);
1274
+ this.nonce++;
1275
+ return plaintext;
1276
+ }
1277
+ get hasKey() {
1278
+ return this.key !== null;
1279
+ }
1280
+ _clear() {
1281
+ sodium$5.sodium_memzero(this.key);
1282
+ this.key = null;
1283
+ this.nonce = null;
1284
+ }
1285
+ static get MACBYTES() {
1286
+ return 16;
1287
+ }
1288
+ static get NONCEBYTES() {
1289
+ return 8;
1290
+ }
1291
+ static get KEYBYTES() {
1292
+ return 32;
1293
+ }
1294
+ };
1295
+ function encryptWithAD(key, counter, additionalData, plaintext) {
1296
+ if (!b4a$14.isBuffer(additionalData)) additionalData = b4a$14.from(additionalData, "hex");
1297
+ if (!b4a$14.isBuffer(plaintext)) plaintext = b4a$14.from(plaintext, "hex");
1298
+ const nonce = b4a$14.alloc(sodium$5.crypto_aead_chacha20poly1305_ietf_NPUBBYTES);
1299
+ new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength).setUint32(4, counter, true);
1300
+ const ciphertext = b4a$14.alloc(plaintext.byteLength + sodium$5.crypto_aead_chacha20poly1305_ietf_ABYTES);
1301
+ sodium$5.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key);
1302
+ return ciphertext;
1303
+ }
1304
+ function decryptWithAD(key, counter, additionalData, ciphertext) {
1305
+ if (!b4a$14.isBuffer(additionalData)) additionalData = b4a$14.from(additionalData, "hex");
1306
+ if (!b4a$14.isBuffer(ciphertext)) ciphertext = b4a$14.from(ciphertext, "hex");
1307
+ const nonce = b4a$14.alloc(sodium$5.crypto_aead_chacha20poly1305_ietf_NPUBBYTES);
1308
+ new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength).setUint32(4, counter, true);
1309
+ const plaintext = b4a$14.alloc(ciphertext.byteLength - sodium$5.crypto_aead_chacha20poly1305_ietf_ABYTES);
1310
+ sodium$5.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key);
1311
+ return plaintext;
1312
+ }
1313
+ }));
1314
+ //#endregion
1315
+ //#region ../../node_modules/hyperdht/node_modules/noise-handshake/dh.js
1316
+ var require_dh = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1317
+ var { crypto_kx_SEEDBYTES, crypto_kx_keypair, crypto_kx_seed_keypair, crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES, crypto_scalarmult, crypto_scalarmult_base } = __require("sodium-universal");
1318
+ var assert$2 = __require("nanoassert");
1319
+ var b4a$13 = __require("b4a");
1320
+ var DHLEN = crypto_scalarmult_BYTES;
1321
+ var PKLEN = crypto_scalarmult_BYTES;
1322
+ var SKLEN = crypto_scalarmult_SCALARBYTES;
1323
+ module.exports = {
1324
+ DHLEN,
1325
+ PKLEN,
1326
+ SKLEN,
1327
+ SEEDLEN: crypto_kx_SEEDBYTES,
1328
+ ALG: "25519",
1329
+ generateKeyPair,
1330
+ generateSeedKeyPair,
1331
+ dh
1332
+ };
1333
+ function generateKeyPair(privKey) {
1334
+ const keyPair = {};
1335
+ keyPair.secretKey = privKey || b4a$13.alloc(SKLEN);
1336
+ keyPair.publicKey = b4a$13.alloc(PKLEN);
1337
+ if (privKey) crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey);
1338
+ else crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey);
1339
+ return keyPair;
1340
+ }
1341
+ function generateSeedKeyPair(seed) {
1342
+ assert$2(seed.byteLength === SKLEN);
1343
+ const keyPair = {};
1344
+ keyPair.secretKey = b4a$13.alloc(SKLEN);
1345
+ keyPair.publicKey = b4a$13.alloc(PKLEN);
1346
+ crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed);
1347
+ return keyPair;
1348
+ }
1349
+ function dh(publicKey, { secretKey }) {
1350
+ assert$2(secretKey.byteLength === SKLEN);
1351
+ assert$2(publicKey.byteLength === PKLEN);
1352
+ const output = b4a$13.alloc(DHLEN);
1353
+ crypto_scalarmult(output, secretKey, publicKey);
1354
+ return output;
1355
+ }
1356
+ }));
1357
+ //#endregion
1358
+ //#region ../../node_modules/hyperdht/node_modules/noise-handshake/hmac.js
1359
+ var require_hmac = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1360
+ var b4a$12 = __require("b4a");
1361
+ var { sodium_memzero, crypto_generichash, crypto_generichash_batch } = __require("sodium-universal");
1362
+ var HASHLEN = 64;
1363
+ var BLOCKLEN = 128;
1364
+ var scratch = b4a$12.alloc(384);
1365
+ var HMACKey = scratch.subarray(0, 128);
1366
+ var OuterKeyPad = scratch.subarray(128, 256);
1367
+ var InnerKeyPad = scratch.subarray(256, 384);
1368
+ module.exports = function hmac(out, batch, key) {
1369
+ if (key.byteLength > BLOCKLEN) {
1370
+ crypto_generichash(HMACKey.subarray(0, HASHLEN), key);
1371
+ sodium_memzero(HMACKey.subarray(HASHLEN));
1372
+ } else {
1373
+ HMACKey.set(key);
1374
+ sodium_memzero(HMACKey.subarray(key.byteLength));
1375
+ }
1376
+ for (let i = 0; i < HMACKey.byteLength; i++) {
1377
+ OuterKeyPad[i] = 92 ^ HMACKey[i];
1378
+ InnerKeyPad[i] = 54 ^ HMACKey[i];
1379
+ }
1380
+ sodium_memzero(HMACKey);
1381
+ crypto_generichash_batch(out, [InnerKeyPad].concat(batch));
1382
+ sodium_memzero(InnerKeyPad);
1383
+ crypto_generichash_batch(out, [OuterKeyPad, out]);
1384
+ sodium_memzero(OuterKeyPad);
1385
+ };
1386
+ module.exports.BYTES = HASHLEN;
1387
+ module.exports.KEYBYTES = BLOCKLEN;
1388
+ }));
1389
+ //#endregion
1390
+ //#region ../../node_modules/hyperdht/node_modules/noise-handshake/hkdf.js
1391
+ var require_hkdf = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1392
+ var hmacBlake2b = require_hmac();
1393
+ var b4a$11 = __require("b4a");
1394
+ var HASHLEN = 64;
1395
+ module.exports = {
1396
+ hkdf,
1397
+ HASHLEN
1398
+ };
1399
+ function hkdf(salt, inputKeyMaterial, info = "", length = 128) {
1400
+ return hkdfExpand(hkdfExtract(salt, inputKeyMaterial), info, length);
1401
+ }
1402
+ function hkdfExtract(salt, inputKeyMaterial) {
1403
+ return hmacDigest(b4a$11.alloc(HASHLEN), salt, inputKeyMaterial);
1404
+ }
1405
+ function hkdfExpand(key, info, length) {
1406
+ const buffer = b4a$11.allocUnsafeSlow(length);
1407
+ const infoBuf = b4a$11.from(info);
1408
+ let prev = infoBuf;
1409
+ const result = [];
1410
+ for (let i = 0; i < length; i += HASHLEN) {
1411
+ const pos = b4a$11.from([i / HASHLEN + 1]);
1412
+ const out = buffer.subarray(i, i + HASHLEN);
1413
+ result.push(out);
1414
+ prev = hmacDigest(out, key, [
1415
+ prev,
1416
+ infoBuf,
1417
+ pos
1418
+ ]);
1419
+ }
1420
+ return result;
1421
+ }
1422
+ function hmacDigest(out, key, input) {
1423
+ hmacBlake2b(out, input, key);
1424
+ return out;
1425
+ }
1426
+ }));
1427
+ //#endregion
1428
+ //#region ../../node_modules/hyperdht/node_modules/noise-handshake/symmetric-state.js
1429
+ var require_symmetric_state = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1430
+ var sodium$4 = __require("sodium-universal");
1431
+ var assert$1 = __require("nanoassert");
1432
+ var b4a$10 = __require("b4a");
1433
+ var CipherState = require_cipher();
1434
+ var curve = require_dh();
1435
+ var { HASHLEN, hkdf } = require_hkdf();
1436
+ module.exports = class SymmetricState extends CipherState {
1437
+ constructor(opts = {}) {
1438
+ super();
1439
+ this.curve = opts.curve || curve;
1440
+ this.digest = b4a$10.alloc(HASHLEN);
1441
+ this.chainingKey = null;
1442
+ this.offset = 0;
1443
+ this.DH_ALG = this.curve.ALG;
1444
+ }
1445
+ mixHash(data) {
1446
+ accumulateDigest(this.digest, data);
1447
+ }
1448
+ mixKeyAndHash(key) {
1449
+ const [ck, tempH, tempK] = hkdf(this.chainingKey, key, "", 3 * HASHLEN);
1450
+ this.chainingKey = ck;
1451
+ this.mixHash(tempH);
1452
+ this.initialiseKey(tempK.subarray(0, 32));
1453
+ }
1454
+ mixKeyNormal(key) {
1455
+ const [ck, tempK] = hkdf(this.chainingKey, key);
1456
+ this.chainingKey = ck;
1457
+ this.initialiseKey(tempK.subarray(0, 32));
1458
+ }
1459
+ mixKey(remoteKey, localKey) {
1460
+ const dh = this.curve.dh(remoteKey, localKey);
1461
+ const hkdfResult = hkdf(this.chainingKey, dh);
1462
+ this.chainingKey = hkdfResult[0];
1463
+ this.initialiseKey(hkdfResult[1].subarray(0, 32));
1464
+ }
1465
+ encryptAndHash(plaintext) {
1466
+ const ciphertext = this.encrypt(plaintext, this.digest);
1467
+ accumulateDigest(this.digest, ciphertext);
1468
+ return ciphertext;
1469
+ }
1470
+ decryptAndHash(ciphertext) {
1471
+ const plaintext = this.decrypt(ciphertext, this.digest);
1472
+ accumulateDigest(this.digest, ciphertext);
1473
+ return plaintext;
1474
+ }
1475
+ getHandshakeHash(out) {
1476
+ if (!out) return this.getHandshakeHash(b4a$10.alloc(HASHLEN));
1477
+ assert$1(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`);
1478
+ out.set(this.digest);
1479
+ return out;
1480
+ }
1481
+ split() {
1482
+ return hkdf(this.chainingKey, b4a$10.alloc(0)).map((k) => k.subarray(0, 32));
1483
+ }
1484
+ _clear() {
1485
+ super._clear();
1486
+ sodium$4.sodium_memzero(this.digest);
1487
+ sodium$4.sodium_memzero(this.chainingKey);
1488
+ this.digest = null;
1489
+ this.chainingKey = null;
1490
+ this.offset = null;
1491
+ this.curve = null;
1492
+ }
1493
+ static get alg() {
1494
+ return CipherState.alg + "_BLAKE2b";
1495
+ }
1496
+ };
1497
+ function accumulateDigest(digest, input) {
1498
+ const toHash = b4a$10.concat([digest, input]);
1499
+ sodium$4.crypto_generichash(digest, toHash);
1500
+ }
1501
+ }));
1502
+ //#endregion
1503
+ //#region ../../node_modules/hyperdht/node_modules/noise-handshake/noise.js
1504
+ var require_noise = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1505
+ var assert = __require("nanoassert");
1506
+ var b4a$9 = __require("b4a");
1507
+ var SymmetricState = require_symmetric_state();
1508
+ var { HASHLEN } = require_hkdf();
1509
+ var PRESHARE_IS = Symbol("initiator static key preshared");
1510
+ var PRESHARE_RS = Symbol("responder static key preshared");
1511
+ var TOK_PSK = Symbol("psk");
1512
+ var TOK_S = Symbol("s");
1513
+ var TOK_E = Symbol("e");
1514
+ var TOK_ES = Symbol("es");
1515
+ var TOK_SE = Symbol("se");
1516
+ var TOK_EE = Symbol("ee");
1517
+ var TOK_SS = Symbol("ss");
1518
+ var HANDSHAKES = Object.freeze({
1519
+ NN: [[TOK_E], [TOK_E, TOK_EE]],
1520
+ NNpsk0: [[TOK_PSK, TOK_E], [TOK_E, TOK_EE]],
1521
+ XX: [
1522
+ [TOK_E],
1523
+ [
1524
+ TOK_E,
1525
+ TOK_EE,
1526
+ TOK_S,
1527
+ TOK_ES
1528
+ ],
1529
+ [TOK_S, TOK_SE]
1530
+ ],
1531
+ XXpsk0: [
1532
+ [TOK_PSK, TOK_E],
1533
+ [
1534
+ TOK_E,
1535
+ TOK_EE,
1536
+ TOK_S,
1537
+ TOK_ES
1538
+ ],
1539
+ [TOK_S, TOK_SE]
1540
+ ],
1541
+ IK: [
1542
+ PRESHARE_RS,
1543
+ [
1544
+ TOK_E,
1545
+ TOK_ES,
1546
+ TOK_S,
1547
+ TOK_SS
1548
+ ],
1549
+ [
1550
+ TOK_E,
1551
+ TOK_EE,
1552
+ TOK_SE
1553
+ ]
1554
+ ],
1555
+ XK: [
1556
+ PRESHARE_RS,
1557
+ [TOK_E, TOK_ES],
1558
+ [TOK_E, TOK_EE],
1559
+ [TOK_S, TOK_SE]
1560
+ ]
1561
+ });
1562
+ var Writer = class {
1563
+ constructor() {
1564
+ this.size = 0;
1565
+ this.buffers = [];
1566
+ }
1567
+ push(b) {
1568
+ this.size += b.byteLength;
1569
+ this.buffers.push(b);
1570
+ }
1571
+ end() {
1572
+ const all = b4a$9.alloc(this.size);
1573
+ let offset = 0;
1574
+ for (const b of this.buffers) {
1575
+ all.set(b, offset);
1576
+ offset += b.byteLength;
1577
+ }
1578
+ return all;
1579
+ }
1580
+ };
1581
+ var Reader = class {
1582
+ constructor(buf) {
1583
+ this.offset = 0;
1584
+ this.buffer = buf;
1585
+ }
1586
+ shift(n) {
1587
+ const start = this.offset;
1588
+ const end = this.offset += n;
1589
+ if (end > this.buffer.byteLength) throw new Error("Insufficient bytes");
1590
+ return this.buffer.subarray(start, end);
1591
+ }
1592
+ end() {
1593
+ return this.shift(this.buffer.byteLength - this.offset);
1594
+ }
1595
+ };
1596
+ module.exports = class NoiseState extends SymmetricState {
1597
+ constructor(pattern, initiator, staticKeypair, opts = {}) {
1598
+ super(opts);
1599
+ this.s = staticKeypair || this.curve.generateKeyPair();
1600
+ this.e = null;
1601
+ this.psk = null;
1602
+ if (opts && opts.psk) this.psk = opts.psk;
1603
+ this.re = null;
1604
+ this.rs = null;
1605
+ this.pattern = pattern;
1606
+ this.handshake = HANDSHAKES[this.pattern].slice();
1607
+ this.isPskHandshake = !!this.psk && hasPskToken(this.handshake);
1608
+ this.protocol = b4a$9.from([
1609
+ "Noise",
1610
+ this.pattern,
1611
+ this.DH_ALG,
1612
+ this.CIPHER_ALG,
1613
+ "BLAKE2b"
1614
+ ].join("_"));
1615
+ this.initiator = initiator;
1616
+ this.complete = false;
1617
+ this.rx = null;
1618
+ this.tx = null;
1619
+ this.hash = null;
1620
+ }
1621
+ initialise(prologue, remoteStatic) {
1622
+ if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol);
1623
+ else this.mixHash(this.protocol);
1624
+ this.chainingKey = b4a$9.from(this.digest);
1625
+ this.mixHash(prologue);
1626
+ while (!Array.isArray(this.handshake[0])) {
1627
+ const message = this.handshake.shift();
1628
+ assert(message === PRESHARE_RS || message === PRESHARE_IS, "Unexpected pattern");
1629
+ const takeRemoteKey = this.initiator ? message === PRESHARE_RS : message === PRESHARE_IS;
1630
+ if (takeRemoteKey) this.rs = remoteStatic;
1631
+ const key = takeRemoteKey ? this.rs : this.s.publicKey;
1632
+ assert(key != null, "Remote pubkey required");
1633
+ this.mixHash(key);
1634
+ }
1635
+ }
1636
+ final() {
1637
+ const [k1, k2] = this.split();
1638
+ this.tx = this.initiator ? k1 : k2;
1639
+ this.rx = this.initiator ? k2 : k1;
1640
+ this.complete = true;
1641
+ this.hash = this.getHandshakeHash();
1642
+ this._clear();
1643
+ }
1644
+ recv(buf) {
1645
+ const r = new Reader(buf);
1646
+ for (const pattern of this.handshake.shift()) switch (pattern) {
1647
+ case TOK_PSK:
1648
+ this.mixKeyAndHash(this.psk);
1649
+ break;
1650
+ case TOK_E:
1651
+ this.re = r.shift(this.curve.PKLEN);
1652
+ this.mixHash(this.re);
1653
+ if (this.isPskHandshake) this.mixKeyNormal(this.re);
1654
+ break;
1655
+ case TOK_S: {
1656
+ const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN;
1657
+ this.rs = this.decryptAndHash(r.shift(klen));
1658
+ break;
1659
+ }
1660
+ case TOK_EE:
1661
+ case TOK_ES:
1662
+ case TOK_SE:
1663
+ case TOK_SS: {
1664
+ const useStatic = keyPattern(pattern, this.initiator);
1665
+ const localKey = useStatic.local ? this.s : this.e;
1666
+ const remoteKey = useStatic.remote ? this.rs : this.re;
1667
+ this.mixKey(remoteKey, localKey);
1668
+ break;
1669
+ }
1670
+ default: throw new Error("Unexpected message");
1671
+ }
1672
+ const payload = this.decryptAndHash(r.end());
1673
+ if (!this.handshake.length) this.final();
1674
+ return payload;
1675
+ }
1676
+ send(payload = b4a$9.alloc(0)) {
1677
+ const w = new Writer();
1678
+ for (const pattern of this.handshake.shift()) switch (pattern) {
1679
+ case TOK_PSK:
1680
+ this.mixKeyAndHash(this.psk);
1681
+ break;
1682
+ case TOK_E:
1683
+ if (this.e === null) this.e = this.curve.generateKeyPair();
1684
+ this.mixHash(this.e.publicKey);
1685
+ if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey);
1686
+ w.push(this.e.publicKey);
1687
+ break;
1688
+ case TOK_S:
1689
+ w.push(this.encryptAndHash(this.s.publicKey));
1690
+ break;
1691
+ case TOK_ES:
1692
+ case TOK_SE:
1693
+ case TOK_EE:
1694
+ case TOK_SS: {
1695
+ const useStatic = keyPattern(pattern, this.initiator);
1696
+ const localKey = useStatic.local ? this.s : this.e;
1697
+ const remoteKey = useStatic.remote ? this.rs : this.re;
1698
+ this.mixKey(remoteKey, localKey);
1699
+ break;
1700
+ }
1701
+ default: throw new Error("Unexpected message");
1702
+ }
1703
+ w.push(this.encryptAndHash(payload));
1704
+ const response = w.end();
1705
+ if (!this.handshake.length) this.final();
1706
+ return response;
1707
+ }
1708
+ _clear() {
1709
+ super._clear();
1710
+ this.e.secretKey.fill(0);
1711
+ this.e.publicKey.fill(0);
1712
+ this.re.fill(0);
1713
+ this.e = null;
1714
+ this.re = null;
1715
+ }
1716
+ };
1717
+ function keyPattern(pattern, initiator) {
1718
+ const ret = {
1719
+ local: false,
1720
+ remote: false
1721
+ };
1722
+ switch (pattern) {
1723
+ case TOK_EE: return ret;
1724
+ case TOK_ES:
1725
+ ret.local ^= !initiator;
1726
+ ret.remote ^= initiator;
1727
+ return ret;
1728
+ case TOK_SE:
1729
+ ret.local ^= initiator;
1730
+ ret.remote ^= !initiator;
1731
+ return ret;
1732
+ case TOK_SS:
1733
+ ret.local ^= 1;
1734
+ ret.remote ^= 1;
1735
+ return ret;
1736
+ }
1737
+ }
1738
+ function hasPskToken(handshake) {
1739
+ return handshake.some((x) => {
1740
+ return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1;
1741
+ });
1742
+ }
1743
+ }));
1744
+ //#endregion
1745
+ //#region ../../node_modules/hyperdht/lib/noise-wrap.js
1746
+ var require_noise_wrap = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1747
+ var NoiseSecretStream$2 = __require("@hyperswarm/secret-stream");
1748
+ var NoiseHandshake = require_noise();
1749
+ var curve = __require("noise-curve-ed");
1750
+ var c$2 = __require("compact-encoding");
1751
+ var b4a$8 = __require("b4a");
1752
+ var sodium$3 = __require("sodium-universal");
1753
+ var m = require_messages();
1754
+ var { NS } = require_constants();
1755
+ var { HANDSHAKE_UNFINISHED } = require_errors();
1756
+ var NOISE_PROLOUGE = NS.PEER_HANDSHAKE;
1757
+ module.exports = class NoiseWrap {
1758
+ constructor(keyPair, remotePublicKey) {
1759
+ this.isInitiator = !!remotePublicKey;
1760
+ this.remotePublicKey = remotePublicKey;
1761
+ this.keyPair = keyPair;
1762
+ this.handshake = new NoiseHandshake("IK", this.isInitiator, keyPair, { curve });
1763
+ this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey);
1764
+ }
1765
+ send(payload) {
1766
+ const buf = c$2.encode(m.noisePayload, payload);
1767
+ return this.handshake.send(buf);
1768
+ }
1769
+ recv(buf) {
1770
+ const payload = c$2.decode(m.noisePayload, this.handshake.recv(buf));
1771
+ this.remotePublicKey = b4a$8.toBuffer(this.handshake.rs);
1772
+ return payload;
1773
+ }
1774
+ final() {
1775
+ if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED();
1776
+ const holepunchSecret = b4a$8.allocUnsafe(32);
1777
+ sodium$3.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash);
1778
+ return {
1779
+ isInitiator: this.isInitiator,
1780
+ publicKey: this.keyPair.publicKey,
1781
+ streamId: this.streamId,
1782
+ remotePublicKey: this.remotePublicKey,
1783
+ remoteId: NoiseSecretStream$2.id(this.handshake.hash, !this.isInitiator),
1784
+ holepunchSecret,
1785
+ hash: b4a$8.toBuffer(this.handshake.hash),
1786
+ rx: b4a$8.toBuffer(this.handshake.rx),
1787
+ tx: b4a$8.toBuffer(this.handshake.tx)
1788
+ };
1789
+ }
1790
+ };
1791
+ }));
1792
+ //#endregion
1793
+ //#region ../../node_modules/hyperdht/lib/sleeper.js
1794
+ var require_sleeper = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1795
+ module.exports = class Sleeper {
1796
+ constructor() {
1797
+ this._timeout = null;
1798
+ this._resolve = null;
1799
+ this._start = (resolve) => {
1800
+ this._resolve = resolve;
1801
+ };
1802
+ this._trigger = () => {
1803
+ if (this._resolve === null) return;
1804
+ const resolve = this._resolve;
1805
+ this._timeout = null;
1806
+ this._resolve = null;
1807
+ resolve();
1808
+ };
1809
+ }
1810
+ pause(ms) {
1811
+ const p = new Promise(this._start);
1812
+ if (this._timeout !== null) {
1813
+ clearTimeout(this._timeout);
1814
+ this._trigger();
1815
+ }
1816
+ this._timeout = setTimeout(this._trigger, ms);
1817
+ return p;
1818
+ }
1819
+ resume() {
1820
+ if (this._timeout !== null) {
1821
+ clearTimeout(this._timeout);
1822
+ this._trigger();
1823
+ }
1824
+ }
1825
+ };
1826
+ }));
1827
+ //#endregion
1828
+ //#region ../../node_modules/hyperdht/lib/announcer.js
1829
+ var require_announcer = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1830
+ var safetyCatch$4 = __require("safety-catch");
1831
+ var c$1 = __require("compact-encoding");
1832
+ var Signal = __require("signal-promise");
1833
+ var { encodeUnslab } = require_encode();
1834
+ var Sleeper = require_sleeper();
1835
+ var m = require_messages();
1836
+ var Persistent = require_persistent();
1837
+ var { COMMANDS } = require_constants();
1838
+ var MIN_ACTIVE = 3;
1839
+ module.exports = class Announcer {
1840
+ constructor(dht, keyPair, target, opts = {}) {
1841
+ this.dht = dht;
1842
+ this.keyPair = keyPair;
1843
+ this.target = target;
1844
+ this.relays = [];
1845
+ this.relayAddresses = [];
1846
+ this.stopped = false;
1847
+ this.suspended = false;
1848
+ this.record = encodeUnslab(m.peer, {
1849
+ publicKey: keyPair.publicKey,
1850
+ relayAddresses: []
1851
+ });
1852
+ this.online = new Signal();
1853
+ this._refreshing = false;
1854
+ this._closestNodes = null;
1855
+ this._active = null;
1856
+ this._sleeper = new Sleeper();
1857
+ this._resumed = new Signal();
1858
+ this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce;
1859
+ this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce;
1860
+ this._updating = null;
1861
+ this._activeQuery = null;
1862
+ this._unannouncing = null;
1863
+ this._serverRelays = [
1864
+ /* @__PURE__ */ new Map(),
1865
+ /* @__PURE__ */ new Map(),
1866
+ /* @__PURE__ */ new Map()
1867
+ ];
1868
+ }
1869
+ isRelay(addr) {
1870
+ const id = addr.host + ":" + addr.port;
1871
+ const [a, b, c] = this._serverRelays;
1872
+ return a.has(id) || b.has(id) || c.has(id);
1873
+ }
1874
+ async suspend({ log = noop } = {}) {
1875
+ if (this.suspended) return;
1876
+ this.suspended = true;
1877
+ log("Suspending announcer");
1878
+ this.online.notify();
1879
+ if (this._activeQuery) this._activeQuery.destroy();
1880
+ this._sleeper.resume();
1881
+ if (this._updating) await this._updating;
1882
+ log("Suspending announcer (post update)");
1883
+ if (this.suspended === false || this.stopped) return;
1884
+ log("Suspending announcer (pre unannounce)");
1885
+ await this._unannounceCurrent();
1886
+ log("Suspending announcer (post unannounce)");
1887
+ }
1888
+ resume() {
1889
+ if (!this.suspended) return;
1890
+ this.suspended = false;
1891
+ this.refresh();
1892
+ this._sleeper.resume();
1893
+ this._resumed.notify();
1894
+ }
1895
+ refresh() {
1896
+ if (this.stopped) return;
1897
+ this._refreshing = true;
1898
+ }
1899
+ async start() {
1900
+ if (this.stopped) return;
1901
+ this._active = this._runUpdate();
1902
+ await this._active;
1903
+ if (this.stopped) return;
1904
+ this._active = this._background();
1905
+ }
1906
+ async stop() {
1907
+ this.stopped = true;
1908
+ this.online.notify();
1909
+ this._sleeper.resume();
1910
+ this._resumed.notify();
1911
+ await this._active;
1912
+ await this._unannounceCurrent();
1913
+ }
1914
+ async _unannounceCurrent() {
1915
+ while (this._unannouncing !== null) await this._unannouncing;
1916
+ const un = this._unannouncing = this._unannounceAll(this._serverRelays[2].values());
1917
+ await this._unannouncing;
1918
+ if (un === this._unannouncing) this._unannouncing = null;
1919
+ }
1920
+ async _background() {
1921
+ while (!this.dht.destroyed && !this.stopped) try {
1922
+ this._refreshing = false;
1923
+ for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
1924
+ const pings = [];
1925
+ for (const node of this._serverRelays[2].values()) pings.push(this.dht.ping(node));
1926
+ if (await resolved(pings) < Math.min(pings.length, MIN_ACTIVE)) this.refresh();
1927
+ if (this.stopped) return;
1928
+ if (!this.suspended && !this._refreshing) await this._sleeper.pause(3e3);
1929
+ }
1930
+ while (!this.stopped && this.suspended) await this._resumed.wait();
1931
+ if (!this.stopped) await this._runUpdate();
1932
+ while (!this.dht.online && !this.stopped && !this.suspended) await this.online.wait();
1933
+ } catch (err) {
1934
+ safetyCatch$4(err);
1935
+ }
1936
+ }
1937
+ async _runUpdate() {
1938
+ this._updating = this._update();
1939
+ await this._updating;
1940
+ this._updating = null;
1941
+ }
1942
+ async _update() {
1943
+ while (this._unannouncing) await this._unannouncing;
1944
+ this._cycle();
1945
+ const q = this._activeQuery = this.dht.findPeer(this.target, {
1946
+ hash: false,
1947
+ nodes: this._closestNodes
1948
+ });
1949
+ try {
1950
+ await q.finished();
1951
+ } catch {}
1952
+ this._activeQuery = null;
1953
+ if (this.stopped || this.suspended) return;
1954
+ const ann = [];
1955
+ const replies = pickBest(q.closestReplies);
1956
+ const relays = [];
1957
+ const relayAddresses = [];
1958
+ if (!this.dht.firewalled) {
1959
+ const addr = this.dht.remoteAddress();
1960
+ if (addr) relayAddresses.push(addr);
1961
+ }
1962
+ for (const msg of replies) ann.push(this._commit(msg, relays, relayAddresses));
1963
+ await Promise.allSettled(ann);
1964
+ if (this.stopped || this.suspended) return;
1965
+ this._closestNodes = q.closestNodes;
1966
+ this.relays = relays;
1967
+ this.relayAddresses = relayAddresses;
1968
+ const removed = [];
1969
+ for (const [key, value] of this._serverRelays[1]) if (!this._serverRelays[2].has(key)) removed.push(value);
1970
+ await this._unannounceAll(removed);
1971
+ }
1972
+ _unannounceAll(relays) {
1973
+ const unann = [];
1974
+ for (const r of relays) unann.push(this._unannounce(r));
1975
+ return Promise.allSettled(unann);
1976
+ }
1977
+ async _unannounce(to) {
1978
+ const unann = {
1979
+ peer: {
1980
+ publicKey: this.keyPair.publicKey,
1981
+ relayAddresses: []
1982
+ },
1983
+ refresh: null,
1984
+ signature: null
1985
+ };
1986
+ const { from, token, value } = await this.dht.request({
1987
+ token: null,
1988
+ command: COMMANDS.FIND_PEER,
1989
+ target: this.target,
1990
+ value: null
1991
+ }, to);
1992
+ if (!token || !from.id || !value) return;
1993
+ unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair);
1994
+ await this.dht.request({
1995
+ token,
1996
+ command: COMMANDS.UNANNOUNCE,
1997
+ target: this.target,
1998
+ value: c$1.encode(m.announce, unann)
1999
+ }, to);
2000
+ }
2001
+ async _commit(msg, relays, relayAddresses) {
2002
+ const ann = {
2003
+ peer: {
2004
+ publicKey: this.keyPair.publicKey,
2005
+ relayAddresses: []
2006
+ },
2007
+ refresh: null,
2008
+ signature: null
2009
+ };
2010
+ ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair);
2011
+ if ((await this.dht.request({
2012
+ token: msg.token,
2013
+ command: COMMANDS.ANNOUNCE,
2014
+ target: this.target,
2015
+ value: c$1.encode(m.announce, ann)
2016
+ }, msg.from)).error !== 0) return;
2017
+ if (relayAddresses.length < 3) relayAddresses.push({
2018
+ host: msg.from.host,
2019
+ port: msg.from.port
2020
+ });
2021
+ relays.push({
2022
+ relayAddress: msg.from,
2023
+ peerAddress: msg.to
2024
+ });
2025
+ this._serverRelays[2].set(msg.from.host + ":" + msg.from.port, msg.from);
2026
+ }
2027
+ _cycle() {
2028
+ const tmp = this._serverRelays[0];
2029
+ this._serverRelays[0] = this._serverRelays[1];
2030
+ this._serverRelays[1] = this._serverRelays[2];
2031
+ this._serverRelays[2] = tmp;
2032
+ tmp.clear();
2033
+ }
2034
+ };
2035
+ function resolved(ps) {
2036
+ let replied = 0;
2037
+ let ticks = ps.length + 1;
2038
+ return new Promise((resolve) => {
2039
+ for (const p of ps) p.then(push, tick);
2040
+ tick();
2041
+ function push(v) {
2042
+ replied++;
2043
+ tick();
2044
+ }
2045
+ function tick() {
2046
+ if (--ticks === 0) resolve(replied);
2047
+ }
2048
+ });
2049
+ }
2050
+ function pickBest(replies) {
2051
+ return replies.slice(0, 3);
2052
+ }
2053
+ function noop() {}
2054
+ }));
2055
+ //#endregion
2056
+ //#region ../../node_modules/hyperdht/lib/crypto.js
2057
+ var require_crypto = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2058
+ var sodium$2 = __require("sodium-universal");
2059
+ var b4a$7 = __require("b4a");
2060
+ function hash(data) {
2061
+ const out = b4a$7.allocUnsafe(32);
2062
+ sodium$2.crypto_generichash(out, data);
2063
+ return out;
2064
+ }
2065
+ function unslabbedHash(data) {
2066
+ const out = b4a$7.allocUnsafeSlow(32);
2067
+ sodium$2.crypto_generichash(out, data);
2068
+ return out;
2069
+ }
2070
+ function createKeyPair(seed) {
2071
+ const publicKey = b4a$7.alloc(32);
2072
+ const secretKey = b4a$7.alloc(64);
2073
+ if (seed) sodium$2.crypto_sign_seed_keypair(publicKey, secretKey, seed);
2074
+ else sodium$2.crypto_sign_keypair(publicKey, secretKey);
2075
+ return {
2076
+ publicKey,
2077
+ secretKey
2078
+ };
2079
+ }
2080
+ module.exports = {
2081
+ hash,
2082
+ unslabbedHash,
2083
+ createKeyPair
2084
+ };
2085
+ }));
2086
+ //#endregion
2087
+ //#region ../../node_modules/hyperdht/lib/secure-payload.js
2088
+ var require_secure_payload = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2089
+ var sodium$1 = __require("sodium-universal");
2090
+ var b4a$6 = __require("b4a");
2091
+ var { holepunchPayload } = require_messages();
2092
+ module.exports = class HolepunchPayload {
2093
+ constructor(holepunchSecret) {
2094
+ this._sharedSecret = holepunchSecret;
2095
+ this._localSecret = b4a$6.allocUnsafe(32);
2096
+ sodium$1.randombytes_buf(this._localSecret);
2097
+ }
2098
+ decrypt(buffer) {
2099
+ const state = {
2100
+ start: 24,
2101
+ end: buffer.byteLength - 16,
2102
+ buffer
2103
+ };
2104
+ if (state.end <= state.start) return null;
2105
+ const nonce = buffer.subarray(0, 24);
2106
+ const msg = state.buffer.subarray(state.start, state.end);
2107
+ const cipher = state.buffer.subarray(state.start);
2108
+ if (!sodium$1.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null;
2109
+ try {
2110
+ return holepunchPayload.decode(state);
2111
+ } catch {
2112
+ return null;
2113
+ }
2114
+ }
2115
+ encrypt(payload) {
2116
+ const state = {
2117
+ start: 24,
2118
+ end: 24,
2119
+ buffer: null
2120
+ };
2121
+ holepunchPayload.preencode(state, payload);
2122
+ state.buffer = b4a$6.allocUnsafe(state.end + 16);
2123
+ const nonce = state.buffer.subarray(0, 24);
2124
+ const msg = state.buffer.subarray(state.start, state.end);
2125
+ const cipher = state.buffer.subarray(state.start);
2126
+ holepunchPayload.encode(state, payload);
2127
+ sodium$1.randombytes_buf(nonce);
2128
+ sodium$1.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret);
2129
+ return state.buffer;
2130
+ }
2131
+ token(addr) {
2132
+ const out = b4a$6.allocUnsafe(32);
2133
+ sodium$1.crypto_generichash(out, b4a$6.from(addr.host), this._localSecret);
2134
+ return out;
2135
+ }
2136
+ };
2137
+ }));
2138
+ //#endregion
2139
+ //#region ../../node_modules/hyperdht/lib/nat.js
2140
+ var require_nat = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2141
+ var { FIREWALL } = require_constants();
2142
+ module.exports = class Nat {
2143
+ constructor(dht, session, socket) {
2144
+ this._samplesHost = [];
2145
+ this._samplesFull = [];
2146
+ this._visited = /* @__PURE__ */ new Map();
2147
+ this._resolve = null;
2148
+ this._minSamples = 4;
2149
+ this._autoSampling = false;
2150
+ this.dht = dht;
2151
+ this.session = session;
2152
+ this.socket = socket;
2153
+ this.sampled = 0;
2154
+ this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN;
2155
+ this.addresses = null;
2156
+ this.analyzing = new Promise((resolve) => {
2157
+ this._resolve = resolve;
2158
+ });
2159
+ }
2160
+ autoSample(retry = true) {
2161
+ if (this._autoSampling) return;
2162
+ this._autoSampling = true;
2163
+ const self = this;
2164
+ const socket = this.socket;
2165
+ const maxPings = this._minSamples;
2166
+ let skip = this.dht.nodes.length >= 8 ? 5 : 0;
2167
+ let pending = 0;
2168
+ for (let node = this.dht.nodes.latest; node && this.sampled + pending < maxPings; node = node.prev) {
2169
+ if (skip > 0) {
2170
+ skip--;
2171
+ continue;
2172
+ }
2173
+ const ref = node.host + ":" + node.port;
2174
+ if (this._visited.has(ref)) continue;
2175
+ this._visited.set(ref, 1);
2176
+ pending++;
2177
+ this.session.ping(node, {
2178
+ socket,
2179
+ retry: false
2180
+ }).then(onpong, onskip);
2181
+ }
2182
+ pending++;
2183
+ onskip();
2184
+ function onpong(res) {
2185
+ self.add(res.to, res.from);
2186
+ onskip();
2187
+ }
2188
+ function onskip() {
2189
+ if (--pending === 0 && self.sampled < self._minSamples) {
2190
+ if (retry) {
2191
+ self._autoSampling = false;
2192
+ self.autoSample(false);
2193
+ return;
2194
+ }
2195
+ self._resolve();
2196
+ }
2197
+ }
2198
+ }
2199
+ destroy() {
2200
+ this._autoSampling = true;
2201
+ this._minSamples = 0;
2202
+ this._resolve();
2203
+ }
2204
+ unfreeze() {
2205
+ this.frozen = false;
2206
+ this._updateFirewall();
2207
+ this._updateAddresses();
2208
+ }
2209
+ freeze() {
2210
+ this.frozen = true;
2211
+ }
2212
+ _updateFirewall() {
2213
+ if (!this.dht.firewalled) {
2214
+ this.firewall = FIREWALL.OPEN;
2215
+ return;
2216
+ }
2217
+ if (this.sampled < 3) return;
2218
+ const max = this._samplesFull[0].hits;
2219
+ if (max >= 3) {
2220
+ this.firewall = FIREWALL.CONSISTENT;
2221
+ return;
2222
+ }
2223
+ if (max === 1) {
2224
+ this.firewall = FIREWALL.RANDOM;
2225
+ return;
2226
+ }
2227
+ if (this._samplesHost.length === 1 && this.sampled > 3) {
2228
+ this.firewall = FIREWALL.RANDOM;
2229
+ return;
2230
+ }
2231
+ if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
2232
+ this.firewall = FIREWALL.CONSISTENT;
2233
+ return;
2234
+ }
2235
+ if (this.sampled > 4) this.firewall = FIREWALL.RANDOM;
2236
+ }
2237
+ _updateAddresses() {
2238
+ if (this.firewall === FIREWALL.UNKNOWN) {
2239
+ this.addresses = null;
2240
+ return;
2241
+ }
2242
+ if (this.firewall === FIREWALL.RANDOM) {
2243
+ this.addresses = [this._samplesHost[0]];
2244
+ return;
2245
+ }
2246
+ if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
2247
+ this.addresses = [];
2248
+ for (const addr of this._samplesFull) if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr);
2249
+ }
2250
+ }
2251
+ update() {
2252
+ if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) this.firewall = FIREWALL.UNKNOWN;
2253
+ this._updateFirewall();
2254
+ this._updateAddresses();
2255
+ }
2256
+ add(addr, from) {
2257
+ const ref = from.host + ":" + from.port;
2258
+ if (this._visited.get(ref) === 2) return;
2259
+ this._visited.set(ref, 2);
2260
+ addSample(this._samplesHost, addr.host, 0);
2261
+ addSample(this._samplesFull, addr.host, addr.port);
2262
+ if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) this.update();
2263
+ if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) this._resolve();
2264
+ else if (this.sampled >= this._minSamples) this._resolve();
2265
+ }
2266
+ };
2267
+ function addSample(samples, host, port) {
2268
+ for (let i = 0; i < samples.length; i++) {
2269
+ const s = samples[i];
2270
+ if (s.port !== port || s.host !== host) continue;
2271
+ s.hits++;
2272
+ for (; i > 0; i--) {
2273
+ const prev = samples[i - 1];
2274
+ if (prev.hits >= s.hits) return;
2275
+ samples[i - 1] = s;
2276
+ samples[i] = prev;
2277
+ }
2278
+ return;
2279
+ }
2280
+ samples.push({
2281
+ host,
2282
+ port,
2283
+ hits: 1
2284
+ });
2285
+ }
2286
+ }));
2287
+ //#endregion
2288
+ //#region ../../node_modules/hyperdht/lib/holepuncher.js
2289
+ var require_holepuncher = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2290
+ var b4a$5 = __require("b4a");
2291
+ var Nat = require_nat();
2292
+ var Sleeper = require_sleeper();
2293
+ var { FIREWALL } = require_constants();
2294
+ var BIRTHDAY_SOCKETS = 256;
2295
+ var HOLEPUNCH = b4a$5.from([0]);
2296
+ var HOLEPUNCH_TTL = 5;
2297
+ var DEFAULT_TTL = 64;
2298
+ var MAX_REOPENS = 3;
2299
+ module.exports = class Holepuncher {
2300
+ constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
2301
+ const holder = dht._socketPool.acquire();
2302
+ this.dht = dht;
2303
+ this.session = session;
2304
+ this.nat = new Nat(dht, session, holder.socket);
2305
+ this.nat.autoSample();
2306
+ this.isInitiator = isInitiator;
2307
+ this.onconnect = noop;
2308
+ this.onabort = noop;
2309
+ this.punching = false;
2310
+ this.connected = false;
2311
+ this.destroyed = false;
2312
+ this.randomized = false;
2313
+ this.remoteFirewall = remoteFirewall;
2314
+ this.remoteAddresses = [];
2315
+ this.remoteHolepunching = false;
2316
+ this._sleeper = new Sleeper();
2317
+ this._reopening = null;
2318
+ this._timeout = null;
2319
+ this._punching = null;
2320
+ this._allHolders = [];
2321
+ this._holder = this._addRef(holder);
2322
+ }
2323
+ get socket() {
2324
+ return this._holder.socket;
2325
+ }
2326
+ updateRemote({ punching, firewall, addresses, verified }) {
2327
+ const remoteAddresses = [];
2328
+ if (addresses) for (const addr of addresses) remoteAddresses.push({
2329
+ host: addr.host,
2330
+ port: addr.port,
2331
+ verified: verified === addr.host || this._isVerified(addr.host)
2332
+ });
2333
+ this.remoteFirewall = firewall;
2334
+ this.remoteAddresses = remoteAddresses;
2335
+ this.remoteHolepunching = punching;
2336
+ }
2337
+ _isVerified(host) {
2338
+ for (const addr of this.remoteAddresses) if (addr.verified && addr.host === host) return true;
2339
+ return false;
2340
+ }
2341
+ ping(addr, socket = this._holder.socket) {
2342
+ return holepunch(socket, addr, false);
2343
+ }
2344
+ openSession(addr, socket = this._holder.socket) {
2345
+ return holepunch(socket, addr, true);
2346
+ }
2347
+ async analyze(allowReopen) {
2348
+ await this.nat.analyzing;
2349
+ if (this._unstable()) {
2350
+ if (!allowReopen) return false;
2351
+ if (!this._reopening) this._reopening = this._reopen();
2352
+ return this._reopening;
2353
+ }
2354
+ return true;
2355
+ }
2356
+ _unstable() {
2357
+ const firewall = this.nat.firewall;
2358
+ return this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM || firewall === FIREWALL.UNKNOWN;
2359
+ }
2360
+ _reset() {
2361
+ const prev = this._holder;
2362
+ this._allHolders.pop();
2363
+ this._holder = this._addRef(this.dht._socketPool.acquire());
2364
+ prev.release();
2365
+ this.nat.destroy();
2366
+ this.nat = new Nat(this.dht, this.session, this._holder.socket);
2367
+ this.nat.autoSample();
2368
+ }
2369
+ _addRef(ref) {
2370
+ this._allHolders.push(ref);
2371
+ ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref);
2372
+ return ref;
2373
+ }
2374
+ _onholepunchmessage(_, addr, ref) {
2375
+ if (!this.isInitiator) {
2376
+ holepunch(ref.socket, addr, false);
2377
+ return;
2378
+ }
2379
+ if (this.connected) return;
2380
+ this.connected = true;
2381
+ this.punching = false;
2382
+ for (const r of this._allHolders) {
2383
+ if (r === ref) continue;
2384
+ r.release();
2385
+ }
2386
+ this._allHolders[0] = ref;
2387
+ while (this._allHolders.length > 1) this._allHolders.pop();
2388
+ this._decrementRandomized();
2389
+ this.onconnect(ref.socket, addr.port, addr.host);
2390
+ }
2391
+ _done() {
2392
+ return this.destroyed || this.connected;
2393
+ }
2394
+ async _reopen() {
2395
+ for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
2396
+ this._reset();
2397
+ await this.nat.analyzing;
2398
+ }
2399
+ return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT;
2400
+ }
2401
+ punch() {
2402
+ if (!this._punching) this._punching = this._punch();
2403
+ return this._punching;
2404
+ }
2405
+ async _punch() {
2406
+ if (this._done() || !this.remoteAddresses.length) return false;
2407
+ this.punching = true;
2408
+ const local = coerceFirewall(this.nat.firewall);
2409
+ const remote = coerceFirewall(this.remoteFirewall);
2410
+ let remoteVerifiedAddress = null;
2411
+ for (const addr of this.remoteAddresses) if (addr.verified) {
2412
+ remoteVerifiedAddress = addr;
2413
+ break;
2414
+ }
2415
+ if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
2416
+ this.dht.stats.punches.consistent++;
2417
+ this._consistentProbe();
2418
+ return true;
2419
+ }
2420
+ if (!remoteVerifiedAddress) return false;
2421
+ if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
2422
+ this.dht.stats.punches.random++;
2423
+ this._incrementRandomized();
2424
+ this._randomProbes(remoteVerifiedAddress);
2425
+ return true;
2426
+ }
2427
+ if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
2428
+ this.dht.stats.punches.random++;
2429
+ this._incrementRandomized();
2430
+ await this._openBirthdaySockets(remoteVerifiedAddress);
2431
+ if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress);
2432
+ return true;
2433
+ }
2434
+ return false;
2435
+ }
2436
+ async _consistentProbe() {
2437
+ if (!this.isInitiator) await this._sleeper.pause(1e3);
2438
+ let tries = 0;
2439
+ while (this.punching && tries++ < 10) {
2440
+ for (const addr of this.remoteAddresses) {
2441
+ if (!addr.verified && (tries & 3) !== 0) continue;
2442
+ await holepunch(this._holder.socket, addr, false);
2443
+ }
2444
+ if (this.punching) await this._sleeper.pause(1e3);
2445
+ }
2446
+ this._autoDestroy();
2447
+ }
2448
+ async _randomProbes(remoteAddr) {
2449
+ let tries = 1750;
2450
+ while (this.punching && tries-- > 0) {
2451
+ const addr = {
2452
+ host: remoteAddr.host,
2453
+ port: randomPort()
2454
+ };
2455
+ await holepunch(this._holder.socket, addr, false);
2456
+ if (this.punching) await this._sleeper.pause(20);
2457
+ }
2458
+ this._autoDestroy();
2459
+ }
2460
+ async _keepAliveRandomNat(remoteAddr) {
2461
+ let i = 0;
2462
+ let lowTTLRounds = 1;
2463
+ await this._sleeper.pause(100);
2464
+ let tries = 1750;
2465
+ while (this.punching && tries-- > 0) {
2466
+ if (i === this._allHolders.length) {
2467
+ i = 0;
2468
+ if (lowTTLRounds > 0) lowTTLRounds--;
2469
+ }
2470
+ await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0);
2471
+ if (this.punching) await this._sleeper.pause(20);
2472
+ }
2473
+ this._autoDestroy();
2474
+ }
2475
+ async _openBirthdaySockets(remoteAddr) {
2476
+ while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) await holepunch(this._addRef(this.dht._socketPool.acquire()).socket, remoteAddr, HOLEPUNCH_TTL);
2477
+ }
2478
+ _autoDestroy() {
2479
+ if (!this.connected) this.destroy();
2480
+ }
2481
+ _incrementRandomized() {
2482
+ if (!this.randomized) {
2483
+ this.randomized = true;
2484
+ this.dht._randomPunches++;
2485
+ }
2486
+ }
2487
+ _decrementRandomized() {
2488
+ if (this.randomized) {
2489
+ this.dht._lastRandomPunch = Date.now();
2490
+ this.randomized = false;
2491
+ this.dht._randomPunches--;
2492
+ }
2493
+ }
2494
+ destroy() {
2495
+ if (this.destroyed) return;
2496
+ this.destroyed = true;
2497
+ this.punching = false;
2498
+ for (const ref of this._allHolders) ref.release();
2499
+ this._allHolders = [];
2500
+ this.nat.destroy();
2501
+ if (!this.connected) {
2502
+ this._decrementRandomized();
2503
+ this.onabort();
2504
+ }
2505
+ }
2506
+ static ping(socket, addr) {
2507
+ return holepunch(socket, addr, false);
2508
+ }
2509
+ static localAddresses(socket) {
2510
+ return localAddresses(socket);
2511
+ }
2512
+ static matchAddress(myAddresses, externalAddresses) {
2513
+ return matchAddress(myAddresses, externalAddresses);
2514
+ }
2515
+ };
2516
+ function holepunch(socket, addr, lowTTL) {
2517
+ return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL);
2518
+ }
2519
+ function randomPort() {
2520
+ return 1e3 + Math.random() * 64536 | 0;
2521
+ }
2522
+ function coerceFirewall(fw) {
2523
+ return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw;
2524
+ }
2525
+ function localAddresses(socket) {
2526
+ const addrs = [];
2527
+ const { host, port } = socket.address();
2528
+ if (host === "127.0.0.1") return [{
2529
+ host,
2530
+ port
2531
+ }];
2532
+ for (const n of socket.udx.networkInterfaces()) {
2533
+ if (n.family !== 4 || n.internal) continue;
2534
+ addrs.push({
2535
+ host: n.host,
2536
+ port
2537
+ });
2538
+ }
2539
+ if (addrs.length === 0) addrs.push({
2540
+ host: "127.0.0.1",
2541
+ port
2542
+ });
2543
+ return addrs;
2544
+ }
2545
+ function matchAddress(localAddresses, remoteLocalAddresses) {
2546
+ if (remoteLocalAddresses.length === 0) return null;
2547
+ let best = {
2548
+ segment: 1,
2549
+ addr: null
2550
+ };
2551
+ for (const localAddress of localAddresses) {
2552
+ const a = localAddress.host.split(".");
2553
+ for (const remoteAddress of remoteLocalAddresses) {
2554
+ const b = remoteAddress.host.split(".");
2555
+ if (a[0] === b[0]) {
2556
+ if (best.segment === 1) best = {
2557
+ segment: 2,
2558
+ addr: remoteAddress
2559
+ };
2560
+ if (a[1] === b[1]) {
2561
+ if (best.segment === 2) best = {
2562
+ segment: 3,
2563
+ addr: remoteAddress
2564
+ };
2565
+ if (a[2] === b[2]) return remoteAddress;
2566
+ }
2567
+ }
2568
+ }
2569
+ }
2570
+ return best.addr;
2571
+ }
2572
+ function noop() {}
2573
+ }));
2574
+ //#endregion
2575
+ //#region ../../node_modules/hyperdht/lib/relay-connection.js
2576
+ var require_relay_connection = /* @__PURE__ */ __commonJSMin(((exports) => {
2577
+ var b4a$4 = __require("b4a");
2578
+ var safetyCatch$3 = __require("safety-catch");
2579
+ exports.clearRelayTimeout = clearRelayTimeout;
2580
+ exports.closeRelayConnection = closeRelayConnection;
2581
+ exports.confirmDirectUpgrade = confirmDirectUpgrade;
2582
+ exports.destroyRelayConnection = destroyRelayConnection;
2583
+ function clearRelayTimeout(connectionOrHandshake) {
2584
+ clearTimeout(connectionOrHandshake.relayTimeout);
2585
+ connectionOrHandshake.relayTimeout = null;
2586
+ }
2587
+ function closeRelayConnection(connectionOrHandshake) {
2588
+ const socket = resetRelayConnection(connectionOrHandshake);
2589
+ if (socket) socket.end();
2590
+ }
2591
+ function confirmDirectUpgrade(connectionOrHandshake, rawStream, remoteChanging) {
2592
+ const cleanup = () => {
2593
+ rawStream.off("data", ondirect);
2594
+ rawStream.off("message", ondirect);
2595
+ rawStream.off("close", cleanup);
2596
+ };
2597
+ function ondirect() {
2598
+ if (!connectionOrHandshake.validUpgrade) {
2599
+ connectionOrHandshake.validUpgrade = true;
2600
+ return;
2601
+ }
2602
+ cleanup();
2603
+ closeRelayConnection(connectionOrHandshake);
2604
+ }
2605
+ const confirm = () => {
2606
+ rawStream.on("data", ondirect);
2607
+ rawStream.on("message", ondirect);
2608
+ rawStream.once("close", cleanup);
2609
+ if (rawStream.trySend) rawStream.trySend(b4a$4.alloc(0));
2610
+ };
2611
+ if (!remoteChanging) {
2612
+ confirm();
2613
+ return;
2614
+ }
2615
+ remoteChanging.then(confirm).catch(safetyCatch$3);
2616
+ }
2617
+ function destroyRelayConnection(connectionOrHandshake) {
2618
+ const socket = resetRelayConnection(connectionOrHandshake);
2619
+ if (socket) socket.destroy();
2620
+ }
2621
+ function resetRelayConnection(connectionOrHandshake) {
2622
+ if (connectionOrHandshake.relayTimeout) clearRelayTimeout(connectionOrHandshake);
2623
+ const socket = connectionOrHandshake.relaySocket;
2624
+ connectionOrHandshake.relayToken = null;
2625
+ connectionOrHandshake.relaySocket = null;
2626
+ connectionOrHandshake.relayClient = null;
2627
+ return socket;
2628
+ }
2629
+ }));
2630
+ //#endregion
2631
+ //#region ../../node_modules/hyperdht/lib/server.js
2632
+ var require_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2633
+ var { EventEmitter: EventEmitter$1 } = __require("events");
2634
+ var safetyCatch$2 = __require("safety-catch");
2635
+ var NoiseSecretStream$1 = __require("@hyperswarm/secret-stream");
2636
+ var b4a$3 = __require("b4a");
2637
+ var relay$1 = __require("blind-relay");
2638
+ var NoiseWrap = require_noise_wrap();
2639
+ var Announcer = require_announcer();
2640
+ var { FIREWALL, ERROR } = require_constants();
2641
+ var { unslabbedHash } = require_crypto();
2642
+ var SecurePayload = require_secure_payload();
2643
+ var Holepuncher = require_holepuncher();
2644
+ var { clearRelayTimeout, confirmDirectUpgrade, destroyRelayConnection } = require_relay_connection();
2645
+ var { isPrivate } = __require("bogon");
2646
+ var { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require_errors();
2647
+ var HANDSHAKE_CLEAR_WAIT = 1e4;
2648
+ var HANDSHAKE_INITIAL_TIMEOUT = 1e4;
2649
+ var RELAY_RECOVERY_WAIT = 3e4;
2650
+ module.exports = class Server extends EventEmitter$1 {
2651
+ constructor(dht, opts = {}) {
2652
+ super();
2653
+ this.dht = dht;
2654
+ this.target = null;
2655
+ this.closed = false;
2656
+ this.firewall = opts.firewall || (() => false);
2657
+ this.holepunch = opts.holepunch || (() => true);
2658
+ this.relayThrough = opts.relayThrough || null;
2659
+ this.relayKeepAlive = opts.relayKeepAlive || 5e3;
2660
+ this.relayRecoveryWait = opts.relayRecoveryWait || RELAY_RECOVERY_WAIT;
2661
+ this.pool = opts.pool || null;
2662
+ this.createHandshake = opts.createHandshake || defaultCreateHandshake;
2663
+ this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream;
2664
+ this.suspended = false;
2665
+ this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT;
2666
+ this._shareLocalAddress = opts.shareLocalAddress !== false;
2667
+ this._reusableSocket = !!opts.reusableSocket;
2668
+ this._neverPunch = opts.holepunch === false;
2669
+ this._keyPair = null;
2670
+ this._announcer = null;
2671
+ this._connects = /* @__PURE__ */ new Map();
2672
+ this._holepunches = [];
2673
+ this._listening = null;
2674
+ this._closing = null;
2675
+ }
2676
+ get listening() {
2677
+ return this._listening !== null;
2678
+ }
2679
+ get publicKey() {
2680
+ return this._keyPair && this._keyPair.publicKey;
2681
+ }
2682
+ get relayAddresses() {
2683
+ return this._announcer ? this._announcer.relayAddresses : [];
2684
+ }
2685
+ onconnection(encryptedSocket) {
2686
+ this.emit("connection", encryptedSocket);
2687
+ }
2688
+ async suspend({ log = noop } = {}) {
2689
+ log("Suspending hyperdht server");
2690
+ if (this._listening !== null) await this._listening;
2691
+ log("Suspending hyperdht server (post listening)");
2692
+ this.suspended = true;
2693
+ this._clearAll();
2694
+ return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve();
2695
+ }
2696
+ async resume() {
2697
+ if (this._listening !== null) await this._listening;
2698
+ this.suspended = false;
2699
+ return this._announcer ? this._announcer.resume() : Promise.resolve();
2700
+ }
2701
+ address() {
2702
+ if (!this._keyPair) return null;
2703
+ return {
2704
+ publicKey: this._keyPair.publicKey,
2705
+ host: this.dht.host,
2706
+ port: this.dht.port
2707
+ };
2708
+ }
2709
+ close() {
2710
+ if (this._closing) return this._closing;
2711
+ this._closing = this._close();
2712
+ return this._closing;
2713
+ }
2714
+ _gc() {
2715
+ this.dht.listening.delete(this);
2716
+ if (this.target) this.dht._router.delete(this.target);
2717
+ }
2718
+ async _stopListening() {
2719
+ try {
2720
+ if (this._announcer) await this._announcer.stop();
2721
+ } catch {}
2722
+ this._announcer = null;
2723
+ this._listening = null;
2724
+ this._keyPair = null;
2725
+ }
2726
+ async _close() {
2727
+ if (this._listening === null) {
2728
+ this.closed = true;
2729
+ this.emit("close");
2730
+ return;
2731
+ }
2732
+ try {
2733
+ await this._listening;
2734
+ } catch (err) {
2735
+ safetyCatch$2(err);
2736
+ }
2737
+ this._gc();
2738
+ this._clearAll();
2739
+ await this._stopListening();
2740
+ this.closed = true;
2741
+ this.emit("close");
2742
+ }
2743
+ _clearAll() {
2744
+ while (this._holepunches.length > 0) {
2745
+ const h = this._holepunches.pop();
2746
+ if (h && h.puncher) h.puncher.destroy();
2747
+ if (h && h.clearing) clearTimeout(h.clearing);
2748
+ if (h && h.prepunching) clearTimeout(h.prepunching);
2749
+ if (h) clearRelayRecovery(h);
2750
+ if (h && h.rawStream) h.rawStream.destroy();
2751
+ }
2752
+ this._connects.clear();
2753
+ }
2754
+ async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
2755
+ if (this._listening !== null) throw ALREADY_LISTENING();
2756
+ if (this.dht.destroyed) throw NODE_DESTROYED();
2757
+ this._listening = this._listen(keyPair, opts);
2758
+ await this._listening;
2759
+ return this;
2760
+ }
2761
+ async _listen(keyPair, opts) {
2762
+ this.dht.listening.add(this);
2763
+ try {
2764
+ await this.dht.bind();
2765
+ if (this._closing) return;
2766
+ for (const s of this.dht.listening) if (s._keyPair && b4a$3.equals(s._keyPair.publicKey, keyPair.publicKey)) throw KEYPAIR_ALREADY_USED();
2767
+ this.target = unslabbedHash(keyPair.publicKey);
2768
+ this._keyPair = keyPair;
2769
+ this._announcer = new Announcer(this.dht, keyPair, this.target, opts);
2770
+ this.dht._router.set(this.target, {
2771
+ relay: null,
2772
+ record: this._announcer.record,
2773
+ onpeerhandshake: this._onpeerhandshake.bind(this),
2774
+ onpeerholepunch: this._onpeerholepunch.bind(this)
2775
+ });
2776
+ this._localAddresses().catch(safetyCatch$2);
2777
+ await this._announcer.start();
2778
+ } catch (err) {
2779
+ await this._stopListening();
2780
+ this._gc();
2781
+ throw err;
2782
+ }
2783
+ if (this._closing) return;
2784
+ if (this.suspended) await this._announcer.suspend();
2785
+ if (this._closing) return;
2786
+ if (this.dht.destroyed) throw NODE_DESTROYED();
2787
+ if (this.pool) this.pool._attachServer(this);
2788
+ this.emit("listening");
2789
+ }
2790
+ refresh() {
2791
+ if (this._announcer && !this.suspended) this._announcer.refresh();
2792
+ }
2793
+ notifyOnline() {
2794
+ if (this._announcer) this._announcer.online.notify();
2795
+ }
2796
+ _localAddresses() {
2797
+ return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket));
2798
+ }
2799
+ async _addHandshake(k, noise, clientAddress, { to: serverAddress, socket }, direct) {
2800
+ let id = this._holepunches.indexOf(null);
2801
+ if (id === -1) id = this._holepunches.push(null) - 1;
2802
+ const hs = {
2803
+ round: 0,
2804
+ reply: null,
2805
+ puncher: null,
2806
+ payload: null,
2807
+ rawStream: null,
2808
+ encryptedSocket: null,
2809
+ prepunching: null,
2810
+ firewalled: true,
2811
+ clearing: null,
2812
+ replyFromPuncher: false,
2813
+ onsocket: null,
2814
+ aborted: false,
2815
+ activeHolepunchRequests: 0,
2816
+ relayTimeout: null,
2817
+ relayToken: null,
2818
+ relaySocket: null,
2819
+ relayClient: null,
2820
+ relayPaired: false,
2821
+ relayFailedAt: null,
2822
+ relayRecoveryTimeout: null,
2823
+ validUpgrade: true
2824
+ };
2825
+ this._holepunches[id] = hs;
2826
+ const handshake = this.createHandshake(this._keyPair, null);
2827
+ let remotePayload;
2828
+ try {
2829
+ remotePayload = await handshake.recv(noise);
2830
+ } catch (err) {
2831
+ safetyCatch$2(err);
2832
+ this._clearLater(hs, id, k);
2833
+ return null;
2834
+ }
2835
+ if (this._closing || this.suspended) {
2836
+ this._clearLater(hs, id, k);
2837
+ return null;
2838
+ }
2839
+ try {
2840
+ hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress);
2841
+ } catch (err) {
2842
+ safetyCatch$2(err);
2843
+ }
2844
+ if (this._closing || this.suspended || hs.firewalled) {
2845
+ this._clearLater(hs, id, k);
2846
+ return null;
2847
+ }
2848
+ const error = remotePayload.version === 1 ? remotePayload.udx ? ERROR.NONE : ERROR.ABORTED : ERROR.VERSION_MISMATCH;
2849
+ const addresses = [];
2850
+ const ourRemoteAddr = this.dht.remoteAddress();
2851
+ const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null;
2852
+ if (this._closing || this.suspended) {
2853
+ this._clearLater(hs, id, k);
2854
+ return null;
2855
+ }
2856
+ if (ourRemoteAddr) addresses.push(ourRemoteAddr);
2857
+ if (ourLocalAddrs) addresses.push(...ourLocalAddrs);
2858
+ if (error === ERROR.NONE) {
2859
+ hs.rawStream = this.dht.createRawStream({
2860
+ framed: true,
2861
+ firewall(socket, port, host) {
2862
+ if (!(port > 0 && port < 65536)) return true;
2863
+ if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
2864
+ hs.validUpgrade = false;
2865
+ return false;
2866
+ }
2867
+ hs.onsocket(socket, port, host);
2868
+ hs.validUpgrade = true;
2869
+ return false;
2870
+ }
2871
+ });
2872
+ hs.rawStream.on("error", autoDestroy);
2873
+ const onrawstreamclose = () => {
2874
+ clearRelayRecovery(hs);
2875
+ if (this._closing) return;
2876
+ if (hs.puncher) {
2877
+ hs.puncher.onabort = noop;
2878
+ hs.puncher.destroy();
2879
+ }
2880
+ this._clearLater(hs, id, k);
2881
+ };
2882
+ hs.rawStream.on("close", onrawstreamclose);
2883
+ hs.onsocket = (socket, port, host) => {
2884
+ if (hs.rawStream === null) return;
2885
+ clearRelayRecovery(hs);
2886
+ this._clearLater(hs, id, k);
2887
+ if (hs.prepunching) {
2888
+ clearTimeout(hs.prepunching);
2889
+ hs.prepunching = null;
2890
+ }
2891
+ if (this._reusableSocket && remotePayload.udx.reusableSocket) this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream);
2892
+ hs.rawStream.removeListener("error", autoDestroy);
2893
+ hs.rawStream.removeListener("close", onrawstreamclose);
2894
+ if (hs.rawStream.connected) {
2895
+ const rawStream = hs.rawStream;
2896
+ const remoteChanging = rawStream.changeRemote(socket, remotePayload.udx.id, port, host);
2897
+ confirmDirectUpgrade(hs, rawStream, remoteChanging);
2898
+ } else {
2899
+ hs.rawStream.connect(socket, remotePayload.udx.id, port, host);
2900
+ hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
2901
+ handshake: h,
2902
+ keepAlive: this.dht.connectionKeepAlive
2903
+ });
2904
+ this.onconnection(hs.encryptedSocket);
2905
+ }
2906
+ if (hs.puncher) {
2907
+ hs.puncher.onabort = noop;
2908
+ hs.puncher.destroy();
2909
+ }
2910
+ hs.rawStream = null;
2911
+ };
2912
+ function autoDestroy() {
2913
+ if (hs.puncher) hs.puncher.destroy();
2914
+ }
2915
+ }
2916
+ const relayAddresses = this.relayAddresses;
2917
+ const relayThrough = selectRelay(this.relayThrough);
2918
+ if (relayThrough) hs.relayToken = relay$1.token();
2919
+ try {
2920
+ hs.reply = await handshake.send({
2921
+ error,
2922
+ firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
2923
+ holepunch: ourRemoteAddr ? null : {
2924
+ id,
2925
+ relays: this._announcer.relays
2926
+ },
2927
+ addresses4: addresses,
2928
+ addresses6: null,
2929
+ udx: {
2930
+ reusableSocket: this._reusableSocket,
2931
+ id: hs.rawStream ? hs.rawStream.id : 0,
2932
+ seq: 0
2933
+ },
2934
+ secretStream: {},
2935
+ relayThrough: relayThrough ? {
2936
+ publicKey: relayThrough,
2937
+ token: hs.relayToken
2938
+ } : null,
2939
+ relayAddresses: relayAddresses.length ? relayAddresses : null
2940
+ });
2941
+ } catch (err) {
2942
+ safetyCatch$2(err);
2943
+ if (hs.rawStream) hs.rawStream.destroy();
2944
+ this._clearLater(hs, id, k);
2945
+ return null;
2946
+ }
2947
+ if (this._closing || this.suspended) {
2948
+ if (hs.rawStream) hs.rawStream.destroy();
2949
+ this._clearLater(hs, id, k);
2950
+ return null;
2951
+ }
2952
+ const h = handshake.final();
2953
+ if (error !== ERROR.NONE) {
2954
+ if (hs.rawStream) hs.rawStream.destroy();
2955
+ this._clearLater(hs, id, k);
2956
+ return hs;
2957
+ }
2958
+ if (remotePayload.firewall === FIREWALL.OPEN || direct) {
2959
+ const sock = direct ? socket : this.dht.socket;
2960
+ this.dht.stats.punches.open++;
2961
+ hs.onsocket(sock, clientAddress.port, clientAddress.host);
2962
+ return hs;
2963
+ }
2964
+ if (relayThrough || remotePayload.relayThrough) this._relayConnection(hs, relayThrough, remotePayload, h);
2965
+ const onabort = () => {
2966
+ hs.aborted = true;
2967
+ clearRelayRecovery(hs);
2968
+ if (hs.prepunching) clearTimeout(hs.prepunching);
2969
+ hs.prepunching = null;
2970
+ if (hs.puncher) {
2971
+ hs.puncher.onabort = noop;
2972
+ hs.puncher.destroy();
2973
+ }
2974
+ if (hs.rawStream.destroyed) {
2975
+ this._clearLater(hs, id, k);
2976
+ return;
2977
+ }
2978
+ hs.rawStream.on("close", () => this._clearLater(hs, id, k));
2979
+ if (hs.relayToken === null) hs.rawStream.destroy();
2980
+ };
2981
+ if (!direct && clientAddress.host === serverAddress.host) {
2982
+ const clientAddresses = remotePayload.addresses4.filter((addr) => isPrivate(addr.host));
2983
+ if (clientAddresses.length > 0 && this._shareLocalAddress) {
2984
+ const myAddresses = await this._localAddresses();
2985
+ if (Holepuncher.matchAddress(myAddresses, clientAddresses)) {
2986
+ hs.payload = new SecurePayload(h.holepunchSecret);
2987
+ setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort);
2988
+ hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT);
2989
+ return hs;
2990
+ }
2991
+ }
2992
+ }
2993
+ if (this._closing || this.suspended) {
2994
+ this._clearLater(hs, id, k);
2995
+ return null;
2996
+ }
2997
+ if (ourRemoteAddr || this._neverPunch) {
2998
+ hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT);
2999
+ return hs;
3000
+ }
3001
+ hs.payload = new SecurePayload(h.holepunchSecret);
3002
+ setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort);
3003
+ hs.replyFromPuncher = true;
3004
+ hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT);
3005
+ return hs;
3006
+ }
3007
+ _clearLater(hs, id, k) {
3008
+ if (hs.clearing) return;
3009
+ hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait);
3010
+ hs.clearing.unref();
3011
+ }
3012
+ _clear(hs, id, k) {
3013
+ clearRelayRecovery(hs);
3014
+ if (id >= this._holepunches.length || this._holepunches[id] !== hs) return;
3015
+ if (hs.clearing) clearTimeout(hs.clearing);
3016
+ this._holepunches[id] = null;
3017
+ while (this._holepunches.length > 0 && this._holepunches[this._holepunches.length - 1] === null) this._holepunches.pop();
3018
+ this._connects.delete(k);
3019
+ }
3020
+ async _onpeerhandshake({ noise, peerAddress }, req) {
3021
+ const k = b4a$3.toString(noise, "hex");
3022
+ let p = this._connects.get(k);
3023
+ if (!p) {
3024
+ p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress);
3025
+ this._connects.set(k, p);
3026
+ }
3027
+ const h = await p;
3028
+ if (!h) return null;
3029
+ if (this._closing !== null || this.suspended) return null;
3030
+ return {
3031
+ socket: h.replyFromPuncher ? h.puncher.socket : null,
3032
+ noise: h.reply
3033
+ };
3034
+ }
3035
+ async _onpeerholepunch({ id, peerAddress, payload }, req) {
3036
+ const h = id < this._holepunches.length ? this._holepunches[id] : null;
3037
+ if (!h) return null;
3038
+ if (!peerAddress || this._closing !== null || this.suspended) return null;
3039
+ if (!h.payload) return this._abort(h);
3040
+ const remotePayload = h.payload.decrypt(payload);
3041
+ if (!remotePayload) return null;
3042
+ const p = h.puncher;
3043
+ if (!p || !p.socket) return this._abort(h);
3044
+ const isServerRelay = this._announcer.isRelay(req.from);
3045
+ const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } = remotePayload;
3046
+ if (error !== ERROR.NONE) {
3047
+ if (round >= h.round) h.round = round;
3048
+ return this._abort(h);
3049
+ }
3050
+ const token = h.payload.token(peerAddress);
3051
+ const echoed = isServerRelay && !!remoteToken && b4a$3.equals(token, remoteToken);
3052
+ if (req.socket === p.socket) p.nat.add(req.to, req.from);
3053
+ if (round >= h.round) {
3054
+ h.round = round;
3055
+ p.updateRemote({
3056
+ punching,
3057
+ firewall,
3058
+ addresses,
3059
+ verified: echoed ? peerAddress.host : null
3060
+ });
3061
+ }
3062
+ h.activeHolepunchRequests++;
3063
+ try {
3064
+ let stable = await p.analyze(false);
3065
+ if (p.destroyed) return null;
3066
+ if (!p.remoteHolepunching && !stable) {
3067
+ stable = await p.analyze(true);
3068
+ if (p.destroyed) return null;
3069
+ if (!stable) return this._abort(h);
3070
+ }
3071
+ if (isConsistent(p.nat.firewall) && remoteAddress && hasSameAddr(p.nat.addresses, remoteAddress)) {
3072
+ await p.ping(peerAddress);
3073
+ if (p.destroyed) return null;
3074
+ }
3075
+ if (p.remoteHolepunching) {
3076
+ if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) return p.destroyed ? null : this._abort(h);
3077
+ if (h.prepunching) {
3078
+ clearTimeout(h.prepunching);
3079
+ h.prepunching = null;
3080
+ }
3081
+ if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
3082
+ if (this.dht._randomPunches >= this.dht._randomPunchLimit || Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval) {
3083
+ this.dht.stats.punches.tryLater++;
3084
+ if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER);
3085
+ if (!h.tryLaterCounted) {
3086
+ h.tryLaterCounted = true;
3087
+ this.dht.stats.punches.tryLaterRelayedHandshakesAtLeastOnce++;
3088
+ }
3089
+ return {
3090
+ socket: p.socket,
3091
+ payload: h.payload.encrypt({
3092
+ error: ERROR.TRY_LATER,
3093
+ firewall: p.nat.firewall,
3094
+ round: h.round,
3095
+ connected: p.connected,
3096
+ punching: p.punching,
3097
+ addresses: p.nat.addresses,
3098
+ remoteAddress: null,
3099
+ token: isServerRelay ? token : null,
3100
+ remoteToken: remotePayload.token
3101
+ })
3102
+ };
3103
+ }
3104
+ }
3105
+ const punching = await p.punch();
3106
+ if (p.destroyed) return null;
3107
+ if (!punching) return this._abort(h);
3108
+ }
3109
+ if (p.nat.firewall !== FIREWALL.UNKNOWN) p.nat.freeze();
3110
+ return {
3111
+ socket: p.socket,
3112
+ payload: h.payload.encrypt({
3113
+ error: ERROR.NONE,
3114
+ firewall: p.nat.firewall,
3115
+ round: h.round,
3116
+ connected: p.connected,
3117
+ punching: p.punching,
3118
+ addresses: p.nat.addresses,
3119
+ remoteAddress: null,
3120
+ token: isServerRelay ? token : null,
3121
+ remoteToken: remotePayload.token
3122
+ })
3123
+ };
3124
+ } finally {
3125
+ h.activeHolepunchRequests--;
3126
+ maybeDestroyRelayHandshake(h, this.relayRecoveryWait);
3127
+ }
3128
+ }
3129
+ _abort(h, error = ERROR.ABORTED) {
3130
+ if (!h.payload) {
3131
+ if (h.puncher) h.puncher.destroy();
3132
+ return null;
3133
+ }
3134
+ const payload = h.payload.encrypt({
3135
+ error,
3136
+ firewall: FIREWALL.UNKNOWN,
3137
+ round: h.round,
3138
+ connected: false,
3139
+ punching: false,
3140
+ addresses: null,
3141
+ remoteAddress: null,
3142
+ token: null,
3143
+ remoteToken: null
3144
+ });
3145
+ if (h.puncher) h.puncher.destroy();
3146
+ return {
3147
+ socket: this.dht.socket,
3148
+ payload
3149
+ };
3150
+ }
3151
+ _relayConnection(hs, relayThrough, remotePayload, h) {
3152
+ this.dht.stats.relaying.attempts++;
3153
+ const relayRecoveryWait = this.relayRecoveryWait;
3154
+ let isInitiator;
3155
+ let publicKey;
3156
+ let token;
3157
+ if (relayThrough) {
3158
+ isInitiator = true;
3159
+ publicKey = relayThrough;
3160
+ token = hs.relayToken;
3161
+ } else {
3162
+ isInitiator = false;
3163
+ publicKey = remotePayload.relayThrough.publicKey;
3164
+ token = remotePayload.relayThrough.token;
3165
+ }
3166
+ const relaySocket = this.dht.connect(publicKey);
3167
+ const relayClient = relay$1.Client.from(relaySocket, { id: relaySocket.publicKey });
3168
+ hs.relayToken = token;
3169
+ hs.relaySocket = relaySocket;
3170
+ hs.relayClient = relayClient;
3171
+ relaySocket.setKeepAlive(this.relayKeepAlive);
3172
+ hs.relayTimeout = setTimeout(onabort, 15e3);
3173
+ relayClient.once("close", onabort);
3174
+ relayClient.pair(isInitiator, token, hs.rawStream).on("error", onabort).on("data", (remoteId) => {
3175
+ if (hs.relayTimeout) clearRelayTimeout(hs);
3176
+ if (hs.rawStream === null) {
3177
+ onabort(null);
3178
+ return;
3179
+ }
3180
+ hs.relayPaired = true;
3181
+ this.dht.stats.relaying.successes++;
3182
+ if (hs.prepunching) clearTimeout(hs.prepunching);
3183
+ hs.prepunching = null;
3184
+ const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream;
3185
+ hs.rawStream.on("close", () => destroyRelayConnection(hs)).connect(socket, remoteId, remotePort, remoteHost);
3186
+ hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
3187
+ handshake: h,
3188
+ keepAlive: this.dht.connectionKeepAlive
3189
+ });
3190
+ this.onconnection(hs.encryptedSocket);
3191
+ });
3192
+ const dht = this.dht;
3193
+ function onabort() {
3194
+ if (hs.relayClient !== relayClient) return;
3195
+ if (!hs.relayPaired && hs.rawStream !== null) dht.stats.relaying.aborts++;
3196
+ hs.relayFailedAt = Date.now();
3197
+ destroyRelayConnection(hs);
3198
+ maybeDestroyRelayHandshake(hs, relayRecoveryWait);
3199
+ }
3200
+ }
3201
+ };
3202
+ function maybeDestroyRelayHandshake(hs, relayRecoveryWait) {
3203
+ if (hs.relayFailedAt === null || hs.rawStream === null || hs.rawStream.destroyed) return;
3204
+ if (hs.aborted) {
3205
+ hs.rawStream.destroy();
3206
+ return;
3207
+ }
3208
+ if (hs.prepunching !== null || hs.activeHolepunchRequests > 0) return;
3209
+ const p = hs.puncher;
3210
+ if (p && p.punching) return;
3211
+ if (!p) {
3212
+ hs.rawStream.destroy();
3213
+ return;
3214
+ }
3215
+ const remaining = relayRecoveryWait - (Date.now() - hs.relayFailedAt);
3216
+ if (remaining > 0) {
3217
+ if (hs.relayRecoveryTimeout !== null) return;
3218
+ hs.relayRecoveryTimeout = setTimeout(() => {
3219
+ hs.relayRecoveryTimeout = null;
3220
+ maybeDestroyRelayHandshake(hs, relayRecoveryWait);
3221
+ }, remaining);
3222
+ hs.relayRecoveryTimeout.unref();
3223
+ return;
3224
+ }
3225
+ hs.rawStream.destroy();
3226
+ }
3227
+ function clearRelayRecovery(hs) {
3228
+ if (hs.relayRecoveryTimeout !== null) clearTimeout(hs.relayRecoveryTimeout);
3229
+ hs.relayRecoveryTimeout = null;
3230
+ hs.relayFailedAt = null;
3231
+ }
3232
+ function isConsistent(fw) {
3233
+ return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT;
3234
+ }
3235
+ function hasSameAddr(addrs, other) {
3236
+ if (addrs === null) return false;
3237
+ for (const addr of addrs) if (addr.port === other.port && addr.host === other.host) return true;
3238
+ return false;
3239
+ }
3240
+ function defaultCreateHandshake(keyPair, remotePublicKey) {
3241
+ return new NoiseWrap(keyPair, remotePublicKey);
3242
+ }
3243
+ function defaultCreateSecretStream(isInitiator, rawStream, opts) {
3244
+ return new NoiseSecretStream$1(isInitiator, rawStream, opts);
3245
+ }
3246
+ function setupHolepuncher(dht, hs, remoteFirewall, onabort) {
3247
+ if (hs.puncher) return;
3248
+ hs.puncher = new Holepuncher(dht, dht.session(), false, remoteFirewall);
3249
+ hs.puncher.onconnect = hs.onsocket;
3250
+ hs.puncher.onabort = onabort;
3251
+ }
3252
+ function isRelay(relaySocket, socket, port, host) {
3253
+ const stream = relaySocket.rawStream;
3254
+ if (!stream) return false;
3255
+ if (stream.socket !== socket) return false;
3256
+ return port === stream.remotePort && host === stream.remoteHost;
3257
+ }
3258
+ function selectRelay(relayThrough) {
3259
+ if (typeof relayThrough === "function") relayThrough = relayThrough();
3260
+ if (relayThrough === null) return null;
3261
+ if (Array.isArray(relayThrough)) return relayThrough[Math.floor(Math.random() * relayThrough.length)];
3262
+ return relayThrough;
3263
+ }
3264
+ function noop() {}
3265
+ }));
3266
+ //#endregion
3267
+ //#region ../../node_modules/hyperdht/lib/semaphore.js
3268
+ var require_semaphore = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3269
+ var DONE = Promise.resolve(true);
3270
+ var DESTROYED = Promise.resolve(false);
3271
+ module.exports = class Semaphore {
3272
+ constructor(limit = 1) {
3273
+ this.limit = limit;
3274
+ this.active = 0;
3275
+ this.waiting = [];
3276
+ this.flushedPromise = null;
3277
+ this.flushedResolve = null;
3278
+ this.destroyed = false;
3279
+ this._onwait = this._queueWaiting.bind(this);
3280
+ this._onflush = this._queueFlushed.bind(this);
3281
+ }
3282
+ _queueWaiting(resolve) {
3283
+ this.waiting.push(resolve);
3284
+ }
3285
+ _queueFlushed(resolve) {
3286
+ this.flushedResolve = resolve;
3287
+ }
3288
+ wait() {
3289
+ if (this.destroyed === true) return DESTROYED;
3290
+ if (this.active < this.limit && this.waiting.length === 0) {
3291
+ this.active++;
3292
+ return DONE;
3293
+ }
3294
+ return new Promise(this._onwait);
3295
+ }
3296
+ signal() {
3297
+ if (this.destroyed === true) return;
3298
+ this.active--;
3299
+ while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
3300
+ this.active++;
3301
+ this.waiting.shift()(true);
3302
+ }
3303
+ if (this.active === 0 && this.flushedResolve) {
3304
+ const resolve = this.flushedResolve;
3305
+ this.flushedResolve = null;
3306
+ this.flushedPromise = null;
3307
+ resolve(true);
3308
+ }
3309
+ }
3310
+ async flush() {
3311
+ if (this.destroyed === true) return;
3312
+ if (this.active === 0) return;
3313
+ if (this.flushedPromise) return this.flushedPromise;
3314
+ this.flushedPromise = new Promise(this._onflush);
3315
+ return this.flushedPromise;
3316
+ }
3317
+ destroy() {
3318
+ this.destroyed = true;
3319
+ this.active = 0;
3320
+ while (this.waiting.length) this.waiting.pop()(false);
3321
+ if (this.flushedResolve) this.flushedResolve(false);
3322
+ }
3323
+ };
3324
+ }));
3325
+ //#endregion
3326
+ //#region ../../node_modules/hyperdht/lib/connect.js
3327
+ var require_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3328
+ var NoiseSecretStream = __require("@hyperswarm/secret-stream");
3329
+ var b4a$2 = __require("b4a");
3330
+ var relay = __require("blind-relay");
3331
+ var { isReserved, isBogon } = __require("bogon");
3332
+ var safetyCatch$1 = __require("safety-catch");
3333
+ var unslab = __require("unslab");
3334
+ var Semaphore = require_semaphore();
3335
+ var NoiseWrap = require_noise_wrap();
3336
+ var SecurePayload = require_secure_payload();
3337
+ var Holepuncher = require_holepuncher();
3338
+ var Sleeper = require_sleeper();
3339
+ var { clearRelayTimeout, confirmDirectUpgrade, destroyRelayConnection } = require_relay_connection();
3340
+ var { FIREWALL, ERROR } = require_constants();
3341
+ var { unslabbedHash } = require_crypto();
3342
+ var { CANNOT_HOLEPUNCH, HANDSHAKE_INVALID, HOLEPUNCH_ABORTED, HOLEPUNCH_INVALID, HOLEPUNCH_PROBE_TIMEOUT, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS, PEER_CONNECTION_FAILED, PEER_NOT_FOUND, REMOTE_ABORTED, REMOTE_NOT_HOLEPUNCHABLE, REMOTE_NOT_HOLEPUNCHING, SERVER_ERROR, SERVER_INCOMPATIBLE, RELAY_ABORTED, SUSPENDED } = require_errors();
3343
+ var { decode } = __require("hypercore-id-encoding");
3344
+ var HyperDHTAddress = __require("hyperdht-address");
3345
+ module.exports = function connect(dht, publicKey, opts = {}) {
3346
+ const pool = opts.pool || null;
3347
+ const { key, nodes: providedNodes } = HyperDHTAddress.decode(b4a$2.isBuffer(publicKey) ? publicKey : decode(publicKey));
3348
+ publicKey = key;
3349
+ if (pool && pool.has(publicKey)) return pool.get(publicKey);
3350
+ publicKey = unslab(publicKey);
3351
+ opts.relayAddresses = opts.relayAddresses || providedNodes || [];
3352
+ const keyPair = opts.keyPair || dht.defaultKeyPair;
3353
+ const relayThrough = selectRelay(opts.relayThrough || null);
3354
+ const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
3355
+ publicKey: keyPair.publicKey,
3356
+ remotePublicKey: publicKey,
3357
+ autoStart: false,
3358
+ keepAlive: dht.connectionKeepAlive
3359
+ });
3360
+ if (dht.suspended || !dht._connectable) {
3361
+ encryptedSocket.destroy(SUSPENDED());
3362
+ return encryptedSocket;
3363
+ }
3364
+ if (pool) pool._attachStream(encryptedSocket, false);
3365
+ const c = {
3366
+ id: b4a$2.toString(publicKey, "hex"),
3367
+ dht,
3368
+ session: dht.session(),
3369
+ relayAddresses: opts.relayAddresses,
3370
+ remoteRelayAddresses: [],
3371
+ pool,
3372
+ round: 0,
3373
+ target: unslabbedHash(publicKey),
3374
+ remotePublicKey: publicKey,
3375
+ reusableSocket: !!opts.reusableSocket,
3376
+ handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
3377
+ request: null,
3378
+ requesting: false,
3379
+ lan: opts.localConnection !== false,
3380
+ firewall: FIREWALL.UNKNOWN,
3381
+ rawStream: dht.createRawStream({
3382
+ framed: true,
3383
+ firewall
3384
+ }),
3385
+ connect: null,
3386
+ query: null,
3387
+ puncher: null,
3388
+ payload: null,
3389
+ passiveConnectTimeout: null,
3390
+ serverSocket: null,
3391
+ serverAddress: null,
3392
+ onsocket: null,
3393
+ sleeper: new Sleeper(),
3394
+ encryptedSocket,
3395
+ relayTimeout: null,
3396
+ relayThrough,
3397
+ relayToken: relayThrough ? relay.token() : null,
3398
+ relaySocket: null,
3399
+ relayClient: null,
3400
+ relayPaired: false,
3401
+ validUpgrade: true,
3402
+ relayKeepAlive: opts.relayKeepAlive || 5e3
3403
+ };
3404
+ c.rawStream.on("error", autoDestroy);
3405
+ c.rawStream.once("connect", () => {
3406
+ c.rawStream.removeListener("error", autoDestroy);
3407
+ });
3408
+ encryptedSocket.on("close", function() {
3409
+ if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c);
3410
+ if (c.query) c.query.destroy();
3411
+ if (c.puncher) c.puncher.destroy();
3412
+ if (c.rawStream) c.rawStream.destroy();
3413
+ c.session.destroy();
3414
+ c.sleeper.resume();
3415
+ });
3416
+ if (dht.suspended) encryptedSocket.destroy(SUSPENDED());
3417
+ else connectAndHolepunch(c, opts);
3418
+ return encryptedSocket;
3419
+ function autoDestroy(err) {
3420
+ maybeDestroyEncryptedSocket(c, err);
3421
+ }
3422
+ function firewall(socket, port, host) {
3423
+ if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
3424
+ c.validUpgrade = false;
3425
+ return false;
3426
+ }
3427
+ c.validUpgrade = true;
3428
+ if (c.onsocket) c.onsocket(socket, port, host);
3429
+ else {
3430
+ c.serverSocket = socket;
3431
+ c.serverAddress = {
3432
+ port,
3433
+ host
3434
+ };
3435
+ }
3436
+ return false;
3437
+ }
3438
+ };
3439
+ function isDone(c) {
3440
+ if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) return true;
3441
+ if (c.encryptedSocket.rawStream === null) return false;
3442
+ if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) return false;
3443
+ return true;
3444
+ }
3445
+ async function retryRoute(c, route) {
3446
+ const ref = c.dht._socketPool.lookup(route.socket);
3447
+ if (!ref) {
3448
+ if (route.socket === c.dht.socket) await connectThroughNode(c, route.address, c.dht.socket);
3449
+ return;
3450
+ }
3451
+ ref.active();
3452
+ try {
3453
+ await connectThroughNode(c, route.address, route.socket);
3454
+ } catch {}
3455
+ ref.inactive();
3456
+ }
3457
+ async function connectAndHolepunch(c, opts) {
3458
+ const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null;
3459
+ if (route) {
3460
+ await retryRoute(c, route);
3461
+ if (isDone(c)) return;
3462
+ }
3463
+ await findAndConnect(c, opts);
3464
+ if (isDone(c)) return;
3465
+ if (!c.connect) {
3466
+ maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID());
3467
+ return;
3468
+ }
3469
+ await holepunch(c, opts);
3470
+ }
3471
+ function getFirstRemoteAddress(addrs, serverAddress) {
3472
+ for (const addr of addrs) {
3473
+ if (isBogon(addr.host)) continue;
3474
+ return addr;
3475
+ }
3476
+ return serverAddress;
3477
+ }
3478
+ async function holepunch(c, opts) {
3479
+ let { relayAddress, serverAddress, clientAddress, payload } = c.connect;
3480
+ const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length);
3481
+ const relayed = diffAddress(serverAddress, relayAddress);
3482
+ if (payload.firewall === FIREWALL.OPEN || relayed && !remoteHolepunchable) {
3483
+ const addr = getFirstRemoteAddress(payload.addresses4, serverAddress);
3484
+ if (addr) {
3485
+ const socket = c.dht.socket;
3486
+ c.dht.stats.punches.open++;
3487
+ c.onsocket(socket, addr.port, addr.host);
3488
+ return;
3489
+ }
3490
+ }
3491
+ const onabort = () => {
3492
+ c.session.destroy();
3493
+ maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED());
3494
+ };
3495
+ if (c.firewall === FIREWALL.OPEN) {
3496
+ c.passiveConnectTimeout = setTimeout(onabort, 1e4);
3497
+ return;
3498
+ }
3499
+ if (c.lan && relayed && clientAddress.host === serverAddress.host) {
3500
+ const serverAddresses = payload.addresses4.filter(onlyNonReserved);
3501
+ if (serverAddresses.length > 0) {
3502
+ const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket);
3503
+ const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0];
3504
+ const socket = c.dht.io.serverSocket;
3505
+ c.dht.ping(addr).then(onlanconnect, onlanerror);
3506
+ if (!remoteHolepunchable) return;
3507
+ function onlanconnect() {
3508
+ if (isDone(c)) return;
3509
+ c.onsocket(socket, addr.port, addr.host);
3510
+ }
3511
+ function onlanerror() {
3512
+ if (!remoteHolepunchable) maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED());
3513
+ }
3514
+ }
3515
+ }
3516
+ if (!remoteHolepunchable) {
3517
+ maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH());
3518
+ return;
3519
+ }
3520
+ c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall);
3521
+ c.puncher.onconnect = c.onsocket;
3522
+ c.puncher.onabort = onabort;
3523
+ const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress);
3524
+ let probe;
3525
+ try {
3526
+ probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true);
3527
+ } catch (err) {
3528
+ destroyPuncher(c);
3529
+ maybeDestroyEncryptedSocket(c, err);
3530
+ return;
3531
+ }
3532
+ if (isDone(c) || !probe) return;
3533
+ const { token, peerAddress } = probe;
3534
+ if (!diffAddress(serverRelay.relayAddress, relayAddress) && diffAddress(serverAddress, peerAddress)) {
3535
+ serverAddress = peerAddress;
3536
+ await c.puncher.openSession(serverAddress);
3537
+ if (isDone(c)) return;
3538
+ }
3539
+ if (opts.holepunch && !opts.holepunch(c.puncher.remoteFirewall, c.puncher.nat.firewall, c.puncher.remoteAddresses, c.puncher.nat.addresses)) {
3540
+ await abort(c, serverRelay, HOLEPUNCH_ABORTED("Client aborted holepunch"));
3541
+ return;
3542
+ }
3543
+ try {
3544
+ await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false);
3545
+ } catch (err) {
3546
+ destroyPuncher(c);
3547
+ maybeDestroyEncryptedSocket(c, err);
3548
+ }
3549
+ }
3550
+ async function connectThroughNodes(c, addresses, socket) {
3551
+ for (const address of addresses) {
3552
+ if (isDone(c) || c.connect) return;
3553
+ c.remoteRelayAddresses.push(address);
3554
+ await connectThroughNode(c, address, socket);
3555
+ }
3556
+ }
3557
+ async function findAndConnect(c, opts) {
3558
+ let attempts = 0;
3559
+ let relayAddresses = opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null;
3560
+ if (!relayAddresses) {
3561
+ const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id);
3562
+ if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses;
3563
+ }
3564
+ if (c.dht._persistent) {
3565
+ const route = c.dht._router.get(c.target);
3566
+ if (route && route.relay !== null) relayAddresses = [{
3567
+ host: route.relay.host,
3568
+ port: route.relay.port
3569
+ }];
3570
+ }
3571
+ const preConnect = relayAddresses !== null && relayAddresses.length > 0;
3572
+ const sem = new Semaphore(preConnect ? 3 : 2);
3573
+ const signal = sem.signal.bind(sem);
3574
+ const tries = relayAddresses !== null ? 2 : 1;
3575
+ if (preConnect) {
3576
+ await sem.wait();
3577
+ connectThroughNodes(c, relayAddresses, null).then(signal, signal);
3578
+ }
3579
+ try {
3580
+ for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
3581
+ c.query = c.dht.findPeer(c.target, {
3582
+ hash: false,
3583
+ session: c.session,
3584
+ nodes: relayAddresses,
3585
+ retries: 3
3586
+ });
3587
+ for await (const data of c.query) {
3588
+ await sem.wait();
3589
+ if (isDone(c)) return;
3590
+ if (c.connect) {
3591
+ sem.signal();
3592
+ break;
3593
+ }
3594
+ if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
3595
+ sem.signal();
3596
+ continue;
3597
+ }
3598
+ c.remoteRelayAddresses.push(data.from);
3599
+ attempts++;
3600
+ connectThroughNode(c, data.from, null).then(signal, signal);
3601
+ }
3602
+ relayAddresses = null;
3603
+ if (attempts > 0) await sem.flush();
3604
+ }
3605
+ c.query = null;
3606
+ if (isDone(c)) return;
3607
+ await sem.flush();
3608
+ if (isDone(c)) return;
3609
+ } catch (err) {
3610
+ c.query = null;
3611
+ maybeDestroyEncryptedSocket(c, err);
3612
+ return;
3613
+ }
3614
+ if (!c.connect) maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND());
3615
+ }
3616
+ async function connectThroughNode(c, address, socket) {
3617
+ if (!c.requesting) {
3618
+ const addr = c.dht.remoteAddress();
3619
+ const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null;
3620
+ const addresses4 = [];
3621
+ if (addr) addresses4.push(addr);
3622
+ if (localAddrs) addresses4.push(...localAddrs);
3623
+ c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN;
3624
+ c.requesting = true;
3625
+ c.request = await c.handshake.send({
3626
+ error: ERROR.NONE,
3627
+ firewall: c.firewall,
3628
+ holepunch: null,
3629
+ addresses4,
3630
+ addresses6: [],
3631
+ udx: {
3632
+ reusableSocket: c.reusableSocket,
3633
+ id: c.rawStream.id,
3634
+ seq: 0
3635
+ },
3636
+ secretStream: {},
3637
+ relayThrough: c.relayThrough ? {
3638
+ publicKey: c.relayThrough,
3639
+ token: c.relayToken
3640
+ } : null
3641
+ });
3642
+ if (isDone(c)) return;
3643
+ }
3644
+ const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(c.target, {
3645
+ noise: c.request,
3646
+ socket,
3647
+ session: c.session
3648
+ }, address);
3649
+ if (isDone(c) || c.connect) return;
3650
+ const payload = await c.handshake.recv(noise);
3651
+ if (isDone(c) || !payload) return;
3652
+ if (payload.version !== 1) {
3653
+ maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE());
3654
+ return;
3655
+ }
3656
+ if (payload.error !== ERROR.NONE) {
3657
+ maybeDestroyEncryptedSocket(c, SERVER_ERROR());
3658
+ return;
3659
+ }
3660
+ if (!payload.udx) {
3661
+ maybeDestroyEncryptedSocket(c, SERVER_ERROR("Server did not send UDX data"));
3662
+ return;
3663
+ }
3664
+ const hs = c.handshake.final();
3665
+ c.handshake = null;
3666
+ c.request = null;
3667
+ c.requesting = false;
3668
+ c.connect = {
3669
+ relayed,
3670
+ relayAddress: address,
3671
+ clientAddress,
3672
+ serverAddress,
3673
+ payload
3674
+ };
3675
+ c.payload = new SecurePayload(hs.holepunchSecret);
3676
+ c.onsocket = function(socket, port, host) {
3677
+ if (c.rawStream === null) return;
3678
+ if (c.rawStream.connected) {
3679
+ const rawStream = c.rawStream;
3680
+ confirmDirectUpgrade(c, rawStream, rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host));
3681
+ } else {
3682
+ if (payload.relayAddresses && payload.relayAddresses.length) c.dht._relayAddressesCache.set(c.id, payload.relayAddresses);
3683
+ else if (c.remoteRelayAddresses.length) c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses);
3684
+ c.rawStream.connect(socket, c.connect.payload.udx.id, port, host);
3685
+ c.encryptedSocket.start(c.rawStream, { handshake: hs });
3686
+ }
3687
+ if (c.reusableSocket && payload.udx.reusableSocket) c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream);
3688
+ if (c.puncher) {
3689
+ c.puncher.onabort = noop;
3690
+ c.puncher.destroy();
3691
+ }
3692
+ if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c);
3693
+ c.rawStream = null;
3694
+ };
3695
+ if (payload.relayThrough || c.relayThrough) relayConnection(c, c.relayThrough, payload, hs);
3696
+ if (c.serverSocket) {
3697
+ c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host);
3698
+ return;
3699
+ }
3700
+ if (!relayed) c.onsocket(socket || c.dht.socket, address.port, address.host);
3701
+ c.session.destroy();
3702
+ }
3703
+ async function updateHolepunch(c, peerAddress, relayAddr, payload) {
3704
+ const holepunch = await c.dht._router.peerHolepunch(c.target, {
3705
+ id: c.connect.payload.holepunch.id,
3706
+ payload: c.payload.encrypt(payload),
3707
+ peerAddress,
3708
+ socket: c.puncher.socket,
3709
+ session: c.session
3710
+ }, relayAddr);
3711
+ if (isDone(c)) return null;
3712
+ const remotePayload = c.payload.decrypt(holepunch.payload);
3713
+ if (!remotePayload) throw HOLEPUNCH_INVALID();
3714
+ const { error, firewall, punching, addresses, remoteToken } = remotePayload;
3715
+ if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) return {
3716
+ tryLater: true,
3717
+ ...holepunch,
3718
+ payload: remotePayload
3719
+ };
3720
+ if (error !== ERROR.NONE) throw REMOTE_ABORTED("Remote aborted with error code " + error);
3721
+ const echoed = !!(remoteToken && payload.token && b4a$2.equals(remoteToken, payload.token));
3722
+ c.puncher.updateRemote({
3723
+ punching,
3724
+ firewall,
3725
+ addresses,
3726
+ verified: echoed ? peerAddress.host : null
3727
+ });
3728
+ return {
3729
+ tryLater: false,
3730
+ ...holepunch,
3731
+ payload: remotePayload
3732
+ };
3733
+ }
3734
+ async function probeRound(c, serverAddress, serverRelay, retry) {
3735
+ if (serverAddress) await c.puncher.openSession(serverAddress);
3736
+ if (isDone(c)) return null;
3737
+ const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
3738
+ error: ERROR.NONE,
3739
+ firewall: c.puncher.nat.firewall,
3740
+ round: c.round++,
3741
+ connected: false,
3742
+ punching: false,
3743
+ addresses: c.puncher.nat.addresses,
3744
+ remoteAddress: serverAddress,
3745
+ token: null,
3746
+ remoteToken: null
3747
+ });
3748
+ if (isDone(c) || !reply) return null;
3749
+ const { peerAddress } = reply;
3750
+ const { address, token } = reply.payload;
3751
+ c.puncher.nat.add(reply.to, reply.from);
3752
+ if (c.puncher.remoteFirewall < FIREWALL.RANDOM && address && address.host && address.port && diffAddress(address, serverAddress)) {
3753
+ await c.puncher.openSession(address);
3754
+ if (isDone(c)) return null;
3755
+ }
3756
+ if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
3757
+ await c.sleeper.pause(1e3);
3758
+ if (isDone(c)) return null;
3759
+ }
3760
+ let stable = await c.puncher.analyze(false);
3761
+ if (isDone(c)) return null;
3762
+ if (!stable) {
3763
+ stable = await c.puncher.analyze(true);
3764
+ if (isDone(c)) return null;
3765
+ if (stable) return probeRound(c, serverAddress, serverRelay, false);
3766
+ }
3767
+ if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) return probeRound(c, serverAddress, serverRelay, false);
3768
+ if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN || c.puncher.nat.firewall === FIREWALL.UNKNOWN) {
3769
+ await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT());
3770
+ return null;
3771
+ }
3772
+ if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
3773
+ await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS());
3774
+ return null;
3775
+ }
3776
+ return {
3777
+ token,
3778
+ peerAddress
3779
+ };
3780
+ }
3781
+ async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
3782
+ c.puncher.nat.freeze();
3783
+ const isRandom = c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM;
3784
+ if (isRandom) while (c.dht._randomPunches >= c.dht._randomPunchLimit || Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval) {
3785
+ if (!c.relayToken) throw HOLEPUNCH_ABORTED();
3786
+ if (!delayed) {
3787
+ delayed = true;
3788
+ await updateHolepunch(c, serverAddress, clientRelay, {
3789
+ error: ERROR.NONE,
3790
+ firewall: c.puncher.nat.firewall,
3791
+ round: c.round++,
3792
+ connected: false,
3793
+ punching: false,
3794
+ addresses: c.puncher.nat.addresses,
3795
+ remoteAddress: null,
3796
+ token: c.payload.token(serverAddress),
3797
+ remoteToken
3798
+ });
3799
+ if (isDone(c)) return;
3800
+ }
3801
+ await tryLater(c);
3802
+ if (isDone(c)) return;
3803
+ }
3804
+ if (isRandom) c.dht._randomPunches++;
3805
+ let reply;
3806
+ try {
3807
+ reply = await updateHolepunch(c, delayed ? serverRelay.peerAddress : serverAddress, delayed ? serverRelay.relayAddress : clientRelay, {
3808
+ error: ERROR.NONE,
3809
+ firewall: c.puncher.nat.firewall,
3810
+ round: c.round++,
3811
+ connected: false,
3812
+ punching: true,
3813
+ addresses: c.puncher.nat.addresses,
3814
+ remoteAddress: null,
3815
+ token: delayed ? null : c.payload.token(serverAddress),
3816
+ remoteToken
3817
+ });
3818
+ } finally {
3819
+ if (isRandom) c.dht._randomPunches--;
3820
+ }
3821
+ if (isDone(c)) return;
3822
+ if (!reply) return;
3823
+ if (reply.tryLater) {
3824
+ await tryLater(c);
3825
+ if (isDone(c)) return;
3826
+ return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true);
3827
+ }
3828
+ if (!c.puncher.remoteHolepunching) throw REMOTE_NOT_HOLEPUNCHING();
3829
+ if (!await c.puncher.punch()) throw REMOTE_NOT_HOLEPUNCHABLE();
3830
+ }
3831
+ async function tryLater(c) {
3832
+ if (!c.relayToken) throw HOLEPUNCH_ABORTED();
3833
+ await c.sleeper.pause(1e4 + Math.round(Math.random() * 1e4));
3834
+ }
3835
+ function maybeDestroyEncryptedSocket(c, err) {
3836
+ if (isDone(c)) return;
3837
+ if (c.encryptedSocket.rawStream) return;
3838
+ if (c.relaySocket) return;
3839
+ if (c.puncher && !c.puncher.destroyed) return;
3840
+ c.session.destroy();
3841
+ c.encryptedSocket.destroy(err);
3842
+ }
3843
+ async function abort(c, { peerAddress, relayAddress }, err) {
3844
+ try {
3845
+ await updateHolepunch(c, peerAddress, relayAddress, {
3846
+ error: ERROR.ABORTED,
3847
+ firewall: FIREWALL.UNKNOWN,
3848
+ round: c.round++,
3849
+ connected: false,
3850
+ punching: false,
3851
+ addresses: null,
3852
+ remoteAddress: null,
3853
+ token: null,
3854
+ remoteToken: null
3855
+ });
3856
+ } catch (err) {
3857
+ safetyCatch$1(err);
3858
+ }
3859
+ destroyPuncher(c);
3860
+ maybeDestroyEncryptedSocket(c, err);
3861
+ }
3862
+ function relayConnection(c, relayThrough, payload, hs) {
3863
+ let isInitiator;
3864
+ let publicKey;
3865
+ let token;
3866
+ if (payload.relayThrough) {
3867
+ isInitiator = false;
3868
+ publicKey = payload.relayThrough.publicKey;
3869
+ token = payload.relayThrough.token;
3870
+ } else {
3871
+ isInitiator = true;
3872
+ publicKey = relayThrough;
3873
+ token = c.relayToken;
3874
+ }
3875
+ c.relayToken = token;
3876
+ c.relaySocket = c.dht.connect(publicKey);
3877
+ c.relaySocket.setKeepAlive(c.relayKeepAlive);
3878
+ c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey });
3879
+ c.relayTimeout = setTimeout(onabort, 15e3, null);
3880
+ c.relayClient.pair(isInitiator, token, c.rawStream).on("error", onabort).on("data", ondata);
3881
+ function ondata(remoteId) {
3882
+ if (c.relayTimeout) clearRelayTimeout(c);
3883
+ if (c.rawStream === null) {
3884
+ onabort(null);
3885
+ return;
3886
+ }
3887
+ c.relayPaired = true;
3888
+ const { remotePort, remoteHost, socket } = c.relaySocket.rawStream;
3889
+ c.rawStream.on("close", () => destroyRelayConnection(c)).connect(socket, remoteId, remotePort, remoteHost);
3890
+ c.encryptedSocket.start(c.rawStream, { handshake: hs });
3891
+ }
3892
+ function onabort(err) {
3893
+ destroyRelayConnection(c);
3894
+ maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED());
3895
+ }
3896
+ }
3897
+ function clearPassiveConnectTimeout(c) {
3898
+ clearTimeout(c.passiveConnectTimeout);
3899
+ c.passiveConnectTimeout = null;
3900
+ }
3901
+ function destroyPuncher(c) {
3902
+ if (c.puncher) c.puncher.destroy();
3903
+ c.session.destroy();
3904
+ }
3905
+ function pickServerRelay(relays, clientRelay) {
3906
+ for (const r of relays) if (!diffAddress(r.relayAddress, clientRelay)) return r;
3907
+ return relays[0];
3908
+ }
3909
+ function diffAddress(a, b) {
3910
+ return a.host !== b.host || a.port !== b.port;
3911
+ }
3912
+ function defaultCreateHandshake(keyPair, remotePublicKey) {
3913
+ return new NoiseWrap(keyPair, remotePublicKey);
3914
+ }
3915
+ function defaultCreateSecretStream(isInitiator, rawStream, opts) {
3916
+ return new NoiseSecretStream(isInitiator, rawStream, opts);
3917
+ }
3918
+ function onlyNonReserved(addr) {
3919
+ return !isReserved(addr.host);
3920
+ }
3921
+ function isRelay(relaySocket, socket, port, host) {
3922
+ const stream = relaySocket.rawStream;
3923
+ if (!stream) return false;
3924
+ if (stream.socket !== socket) return false;
3925
+ return port === stream.remotePort && host === stream.remoteHost;
3926
+ }
3927
+ function selectRelay(relayThrough) {
3928
+ if (typeof relayThrough === "function") relayThrough = relayThrough();
3929
+ if (relayThrough === null) return null;
3930
+ if (Array.isArray(relayThrough)) return relayThrough[Math.floor(Math.random() * relayThrough.length)];
3931
+ return relayThrough;
3932
+ }
3933
+ function isRelayAddress(relayAddresses, data) {
3934
+ for (const node of relayAddresses) if (node.host === data.from.host && node.port === data.from.port) return true;
3935
+ return false;
3936
+ }
3937
+ function noop() {}
3938
+ }));
3939
+ //#endregion
3940
+ //#region ../../node_modules/hyperdht/lib/raw-stream-set.js
3941
+ var require_raw_stream_set = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3942
+ module.exports = class RawStreamSet {
3943
+ constructor(dht) {
3944
+ this._dht = dht;
3945
+ this._prefix = 15;
3946
+ this._streams = /* @__PURE__ */ new Map();
3947
+ }
3948
+ get size() {
3949
+ return this._streams.size;
3950
+ }
3951
+ [Symbol.iterator]() {
3952
+ return this._streams.values();
3953
+ }
3954
+ add(opts) {
3955
+ const self = this;
3956
+ let id = 0;
3957
+ while (true) {
3958
+ id = Math.random() * 4294967296 >>> 0;
3959
+ if (this._streams.has(id & this._prefix)) continue;
3960
+ break;
3961
+ }
3962
+ if (2 * this._streams.size >= this._prefix) {
3963
+ this._prefix = 2 * this._prefix + 1;
3964
+ const next = /* @__PURE__ */ new Map();
3965
+ for (const stream of this._streams.values()) next.set(stream.id & this._prefix, stream);
3966
+ this._streams = next;
3967
+ }
3968
+ const stream = this._dht.udx.createStream(id, opts);
3969
+ this._streams.set(id & this._prefix, stream);
3970
+ stream.on("close", onclose);
3971
+ return stream;
3972
+ function onclose() {
3973
+ self._streams.delete(id & self._prefix);
3974
+ }
3975
+ }
3976
+ async clear() {
3977
+ const destroying = [];
3978
+ for (const stream of this._streams.values()) destroying.push(new Promise((resolve) => stream.once("close", resolve).destroy()));
3979
+ await Promise.allSettled(destroying);
3980
+ }
3981
+ };
3982
+ }));
3983
+ //#endregion
3984
+ //#region ../../node_modules/hyperdht/lib/connection-pool.js
3985
+ var require_connection_pool = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3986
+ var EventEmitter = __require("events");
3987
+ var b4a$1 = __require("b4a");
3988
+ var errors = require_errors();
3989
+ module.exports = class ConnectionPool extends EventEmitter {
3990
+ constructor(dht) {
3991
+ super();
3992
+ this._dht = dht;
3993
+ this._servers = /* @__PURE__ */ new Map();
3994
+ this._connecting = /* @__PURE__ */ new Map();
3995
+ this._connections = /* @__PURE__ */ new Map();
3996
+ }
3997
+ _attachServer(server) {
3998
+ const keyString = b4a$1.toString(server.publicKey, "hex");
3999
+ this._servers.set(keyString, server);
4000
+ server.on("close", () => {
4001
+ this._servers.delete(keyString);
4002
+ }).on("connection", (socket) => {
4003
+ this._attachStream(socket, true);
4004
+ });
4005
+ }
4006
+ _attachStream(stream, opened) {
4007
+ const existing = this.get(stream.remotePublicKey);
4008
+ if (existing) {
4009
+ if (stream.isInitiator === existing.isInitiator || b4a$1.compare(stream.publicKey, stream.remotePublicKey) > 0) {
4010
+ let closed = false;
4011
+ const onclose = () => {
4012
+ closed = true;
4013
+ };
4014
+ existing.on("error", noop).on("close", () => {
4015
+ if (closed) return;
4016
+ stream.off("error", noop).off("close", onclose);
4017
+ this._attachStream(stream, opened);
4018
+ }).destroy(errors.DUPLICATE_CONNECTION());
4019
+ stream.on("error", noop).on("close", onclose);
4020
+ } else stream.on("error", noop).destroy(errors.DUPLICATE_CONNECTION());
4021
+ return;
4022
+ }
4023
+ const session = new ConnectionRef(this, stream);
4024
+ const keyString = b4a$1.toString(stream.remotePublicKey, "hex");
4025
+ if (opened) {
4026
+ this._connections.set(keyString, session);
4027
+ stream.on("close", () => {
4028
+ this._connections.delete(keyString);
4029
+ });
4030
+ this.emit("connection", stream, session);
4031
+ } else {
4032
+ this._connecting.set(keyString, session);
4033
+ stream.on("error", noop).on("close", () => {
4034
+ if (opened) this._connections.delete(keyString);
4035
+ else this._connecting.delete(keyString);
4036
+ }).on("open", () => {
4037
+ opened = true;
4038
+ this._connecting.delete(keyString);
4039
+ this._connections.set(keyString, session);
4040
+ stream.off("error", noop);
4041
+ this.emit("connection", stream, session);
4042
+ });
4043
+ }
4044
+ return session;
4045
+ }
4046
+ get connecting() {
4047
+ return this._connecting.size;
4048
+ }
4049
+ get connections() {
4050
+ return this._connections.values();
4051
+ }
4052
+ has(publicKey) {
4053
+ const keyString = b4a$1.toString(publicKey, "hex");
4054
+ return this._connections.has(keyString) || this._connecting.has(keyString);
4055
+ }
4056
+ get(publicKey) {
4057
+ const keyString = b4a$1.toString(publicKey, "hex");
4058
+ return (this._connections.get(keyString) || this._connecting.get(keyString))?._stream || null;
4059
+ }
4060
+ };
4061
+ var ConnectionRef = class {
4062
+ constructor(pool, stream) {
4063
+ this._pool = pool;
4064
+ this._stream = stream;
4065
+ this._refs = 0;
4066
+ }
4067
+ active() {
4068
+ this._refs++;
4069
+ }
4070
+ inactive() {
4071
+ this._refs--;
4072
+ }
4073
+ release() {
4074
+ this._stream.destroy();
4075
+ }
4076
+ };
4077
+ function noop() {}
4078
+ }));
4079
+ //#endregion
4080
+ //#region ../../native/transports/hyperdht/redial.mjs
4081
+ var import_hyperdht = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
4082
+ var DHT$1 = __require("dht-rpc");
4083
+ var sodium = __require("sodium-universal");
4084
+ var c = __require("compact-encoding");
4085
+ var b4a = __require("b4a");
4086
+ var safetyCatch = __require("safety-catch");
4087
+ var m = require_messages();
4088
+ var SocketPool = require_socket_pool();
4089
+ var Persistent = require_persistent();
4090
+ var Router = require_router();
4091
+ var Cache = __require("xache");
4092
+ var Server = require_server();
4093
+ var connect = require_connect();
4094
+ var { FIREWALL, BOOTSTRAP_NODES, COMMANDS } = require_constants();
4095
+ var { hash, createKeyPair } = require_crypto();
4096
+ var RawStreamSet = require_raw_stream_set();
4097
+ var ConnectionPool = require_connection_pool();
4098
+ var { STREAM_NOT_CONNECTED } = require_errors();
4099
+ var DEFAULTS = {
4100
+ ...DHT$1.DEFAULTS,
4101
+ connectionKeepAlive: 5e3,
4102
+ randomPunchInterval: 2e4
4103
+ };
4104
+ var HyperDHT = class extends DHT$1 {
4105
+ constructor(opts = {}) {
4106
+ const port = opts.port || 49737;
4107
+ const bootstrap = opts.bootstrap || BOOTSTRAP_NODES;
4108
+ const nodes = opts.nodes || [];
4109
+ super({
4110
+ ...opts,
4111
+ port,
4112
+ bootstrap,
4113
+ nodes,
4114
+ filterNode
4115
+ });
4116
+ const { router, relayAddresses, persistent } = defaultCacheOpts(opts);
4117
+ this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed);
4118
+ this.listening = /* @__PURE__ */ new Set();
4119
+ this.connectionKeepAlive = opts.connectionKeepAlive === false ? 0 : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive;
4120
+ this.rawStreams = new RawStreamSet(this);
4121
+ this.plugins = /* @__PURE__ */ new Map();
4122
+ this._router = new Router(this, router);
4123
+ this._socketPool = new SocketPool(this, opts.host || "0.0.0.0");
4124
+ this._persistent = null;
4125
+ this._validatedLocalAddresses = /* @__PURE__ */ new Map();
4126
+ this._relayAddressesCache = new Cache(relayAddresses);
4127
+ this._deferRandomPunch = !!opts.deferRandomPunch;
4128
+ this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0;
4129
+ this._connectable = true;
4130
+ this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval;
4131
+ this._randomPunches = 0;
4132
+ this._randomPunchLimit = 1;
4133
+ this.stats = {
4134
+ punches: {
4135
+ consistent: 0,
4136
+ random: 0,
4137
+ open: 0,
4138
+ tryLater: 0,
4139
+ tryLaterRelayedHandshakesAtLeastOnce: 0
4140
+ },
4141
+ relaying: {
4142
+ attempts: 0,
4143
+ successes: 0,
4144
+ aborts: 0
4145
+ },
4146
+ socketPool: this._socketPool.stats,
4147
+ ...this.stats
4148
+ };
4149
+ this.once("persistent", () => {
4150
+ this._persistent = new Persistent(this, persistent);
4151
+ for (const plugin of this.plugins.values()) plugin.onpersistent();
4152
+ });
4153
+ this.on("network-change", () => {
4154
+ for (const server of this.listening) server.refresh();
4155
+ });
4156
+ this.on("network-update", () => {
4157
+ if (!this.online) return;
4158
+ for (const server of this.listening) server.notifyOnline();
4159
+ });
4160
+ }
4161
+ static DEFAULTS = DEFAULTS;
4162
+ connect(remotePublicKey, opts) {
4163
+ return connect(this, remotePublicKey, opts);
4164
+ }
4165
+ createServer(opts, onconnection) {
4166
+ if (typeof opts === "function") return this.createServer({}, opts);
4167
+ if (opts && opts.onconnection) onconnection = opts.onconnection;
4168
+ const s = new Server(this, opts);
4169
+ if (onconnection) s.on("connection", onconnection);
4170
+ return s;
4171
+ }
4172
+ pool() {
4173
+ return new ConnectionPool(this);
4174
+ }
4175
+ async resume({ log = noop } = {}) {
4176
+ if (this._deferRandomPunch) this._lastRandomPunch = Date.now();
4177
+ await super.resume({ log });
4178
+ const resuming = [];
4179
+ for (const server of this.listening) resuming.push(server.resume());
4180
+ log("Resuming hyperdht servers");
4181
+ await Promise.allSettled(resuming);
4182
+ log("Done, hyperdht fully resumed");
4183
+ }
4184
+ async suspend({ log = noop } = {}) {
4185
+ this._connectable = false;
4186
+ const suspending = [];
4187
+ for (const server of this.listening) suspending.push(server.suspend());
4188
+ log("Suspending all hyperdht servers");
4189
+ await Promise.allSettled(suspending);
4190
+ log("Done, clearing all raw streams");
4191
+ await this.rawStreams.clear();
4192
+ log("Done, suspending dht-rpc");
4193
+ await super.suspend({ log });
4194
+ log("Done, clearing raw streams again");
4195
+ await this.rawStreams.clear();
4196
+ log("Done, hyperdht fully suspended");
4197
+ this._connectable = true;
4198
+ }
4199
+ async destroy({ force = false } = {}) {
4200
+ if (!force) {
4201
+ const closing = [];
4202
+ for (const server of this.listening) closing.push(server.close());
4203
+ await Promise.allSettled(closing);
4204
+ }
4205
+ this._router.destroy();
4206
+ if (this._persistent) this._persistent.destroy();
4207
+ for (const plugin of this.plugins.values()) plugin.destroy();
4208
+ await this.rawStreams.clear();
4209
+ await this._socketPool.destroy();
4210
+ await super.destroy();
4211
+ }
4212
+ async validateLocalAddresses(addresses) {
4213
+ const list = [];
4214
+ const socks = [];
4215
+ const waiting = [];
4216
+ for (const addr of addresses) {
4217
+ const { host } = addr;
4218
+ if (this._validatedLocalAddresses.has(host)) {
4219
+ if (await this._validatedLocalAddresses.get(host)) list.push(addr);
4220
+ continue;
4221
+ }
4222
+ const sock = this.udx.createSocket();
4223
+ try {
4224
+ sock.bind(0, host);
4225
+ } catch {
4226
+ this._validatedLocalAddresses.set(host, Promise.resolve(false));
4227
+ continue;
4228
+ }
4229
+ socks.push(sock);
4230
+ const promise = new Promise((resolve) => {
4231
+ sock.on("message", () => resolve(true));
4232
+ setTimeout(() => resolve(false), 500);
4233
+ sock.trySend(b4a.alloc(1), sock.address().port, addr.host);
4234
+ });
4235
+ this._validatedLocalAddresses.set(host, promise);
4236
+ waiting.push(addr);
4237
+ }
4238
+ for (const addr of waiting) {
4239
+ const { host } = addr;
4240
+ if (this._validatedLocalAddresses.has(host)) {
4241
+ if (await this._validatedLocalAddresses.get(host)) list.push(addr);
4242
+ continue;
4243
+ }
4244
+ }
4245
+ for (const sock of socks) await sock.close();
4246
+ return list;
4247
+ }
4248
+ findPeer(publicKey, opts = {}) {
4249
+ const target = opts.hash === false ? publicKey : hash(publicKey);
4250
+ opts = {
4251
+ ...opts,
4252
+ map: mapFindPeer
4253
+ };
4254
+ return this.query({
4255
+ target,
4256
+ command: COMMANDS.FIND_PEER,
4257
+ value: null
4258
+ }, opts);
4259
+ }
4260
+ lookup(target, opts = {}) {
4261
+ opts = {
4262
+ ...opts,
4263
+ map: mapLookup
4264
+ };
4265
+ return this.query({
4266
+ target,
4267
+ command: COMMANDS.LOOKUP,
4268
+ value: null
4269
+ }, opts);
4270
+ }
4271
+ lookupAndUnannounce(target, keyPair, opts = {}) {
4272
+ const unannounces = [];
4273
+ const dht = this;
4274
+ const userCommit = opts.commit || noop;
4275
+ const signUnannounce = opts.signUnannounce || Persistent.signUnannounce;
4276
+ if (this._persistent !== null) this._persistent.unannounce(target, keyPair.publicKey);
4277
+ opts = {
4278
+ ...opts,
4279
+ map,
4280
+ commit
4281
+ };
4282
+ return this.query({
4283
+ target,
4284
+ command: COMMANDS.LOOKUP,
4285
+ value: null
4286
+ }, opts);
4287
+ async function commit(reply, dht, query) {
4288
+ await Promise.all(unannounces);
4289
+ return userCommit(reply, dht, query);
4290
+ }
4291
+ function map(reply) {
4292
+ const data = mapLookup(reply);
4293
+ if (!data || !data.token) return data;
4294
+ let found = data.peers.length >= 20;
4295
+ for (let i = 0; !found && i < data.peers.length; i++) found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey);
4296
+ if (!found) return data;
4297
+ if (!data.from.id) return data;
4298
+ unannounces.push(dht._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce).catch(safetyCatch));
4299
+ return data;
4300
+ }
4301
+ }
4302
+ unannounce(target, keyPair, opts = {}) {
4303
+ return this.lookupAndUnannounce(target, keyPair, opts).finished();
4304
+ }
4305
+ announce(target, keyPair, relayAddresses, opts = {}) {
4306
+ const signAnnounce = opts.signAnnounce || Persistent.signAnnounce;
4307
+ const bump = opts.bump || 0;
4308
+ opts = {
4309
+ ...opts,
4310
+ commit
4311
+ };
4312
+ return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts);
4313
+ function commit(reply, dht) {
4314
+ return dht._requestAnnounce(keyPair, dht, target, reply.token, reply.from, relayAddresses, signAnnounce, bump);
4315
+ }
4316
+ }
4317
+ async immutableGet(target, opts = {}) {
4318
+ opts = {
4319
+ ...opts,
4320
+ map: mapImmutable
4321
+ };
4322
+ const query = this.query({
4323
+ target,
4324
+ command: COMMANDS.IMMUTABLE_GET,
4325
+ value: null
4326
+ }, opts);
4327
+ const check = b4a.allocUnsafe(32);
4328
+ for await (const node of query) {
4329
+ const { value } = node;
4330
+ sodium.crypto_generichash(check, value);
4331
+ if (b4a.equals(check, target)) return node;
4332
+ }
4333
+ return null;
4334
+ }
4335
+ async immutablePut(value, opts = {}) {
4336
+ const target = b4a.allocUnsafe(32);
4337
+ sodium.crypto_generichash(target, value);
4338
+ opts = {
4339
+ ...opts,
4340
+ map: mapImmutable,
4341
+ commit(reply, dht) {
4342
+ return dht.request({
4343
+ token: reply.token,
4344
+ target,
4345
+ command: COMMANDS.IMMUTABLE_PUT,
4346
+ value
4347
+ }, reply.from);
4348
+ }
4349
+ };
4350
+ const query = this.query({
4351
+ target,
4352
+ command: COMMANDS.IMMUTABLE_GET,
4353
+ value: null
4354
+ }, opts);
4355
+ await query.finished();
4356
+ return {
4357
+ hash: target,
4358
+ closestNodes: query.closestNodes
4359
+ };
4360
+ }
4361
+ async mutableGet(publicKey, opts = {}) {
4362
+ let refresh = opts.refresh || null;
4363
+ let signed = null;
4364
+ let result = null;
4365
+ opts = {
4366
+ ...opts,
4367
+ map: mapMutable,
4368
+ commit: refresh ? commit : null
4369
+ };
4370
+ const target = b4a.allocUnsafe(32);
4371
+ sodium.crypto_generichash(target, publicKey);
4372
+ const userSeq = opts.seq || 0;
4373
+ const query = this.query({
4374
+ target,
4375
+ command: COMMANDS.MUTABLE_GET,
4376
+ value: c.encode(c.uint, userSeq)
4377
+ }, opts);
4378
+ const latest = opts.latest !== false;
4379
+ for await (const node of query) {
4380
+ if (result && node.seq <= result.seq) continue;
4381
+ if (node.seq < userSeq || !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)) continue;
4382
+ if (!latest) return node;
4383
+ if (!result || node.seq > result.seq) result = node;
4384
+ }
4385
+ return result;
4386
+ function commit(reply, dht) {
4387
+ if (!signed && result && refresh) {
4388
+ if (refresh(result)) signed = c.encode(m.mutablePutRequest, {
4389
+ publicKey,
4390
+ seq: result.seq,
4391
+ value: result.value,
4392
+ signature: result.signature
4393
+ });
4394
+ else refresh = null;
4395
+ }
4396
+ return signed ? dht.request({
4397
+ token: reply.token,
4398
+ target,
4399
+ command: COMMANDS.MUTABLE_PUT,
4400
+ value: signed
4401
+ }, reply.from) : Promise.resolve(null);
4402
+ }
4403
+ }
4404
+ async mutablePut(keyPair, value, opts = {}) {
4405
+ const signMutable = opts.signMutable || Persistent.signMutable;
4406
+ const target = b4a.allocUnsafe(32);
4407
+ sodium.crypto_generichash(target, keyPair.publicKey);
4408
+ const seq = opts.seq || 0;
4409
+ const signature = await signMutable(seq, value, keyPair);
4410
+ const signed = c.encode(m.mutablePutRequest, {
4411
+ publicKey: keyPair.publicKey,
4412
+ seq,
4413
+ value,
4414
+ signature
4415
+ });
4416
+ opts = {
4417
+ ...opts,
4418
+ map: mapMutable,
4419
+ commit(reply, dht) {
4420
+ return dht.request({
4421
+ token: reply.token,
4422
+ target,
4423
+ command: COMMANDS.MUTABLE_PUT,
4424
+ value: signed
4425
+ }, reply.from);
4426
+ }
4427
+ };
4428
+ const query = this.query({
4429
+ target,
4430
+ command: COMMANDS.MUTABLE_GET,
4431
+ value: c.encode(c.uint, 0)
4432
+ }, opts);
4433
+ await query.finished();
4434
+ return {
4435
+ publicKey: keyPair.publicKey,
4436
+ closestNodes: query.closestNodes,
4437
+ seq,
4438
+ signature
4439
+ };
4440
+ }
4441
+ onrequest(req) {
4442
+ switch (req.command) {
4443
+ case COMMANDS.PEER_HANDSHAKE:
4444
+ this._router.onpeerhandshake(req);
4445
+ return true;
4446
+ case COMMANDS.PEER_HOLEPUNCH:
4447
+ this._router.onpeerholepunch(req);
4448
+ return true;
4449
+ }
4450
+ if (this._persistent === null || this.id === null) return false;
4451
+ switch (req.command) {
4452
+ case COMMANDS.FIND_PEER:
4453
+ this._persistent.onfindpeer(req);
4454
+ return true;
4455
+ case COMMANDS.LOOKUP:
4456
+ this._persistent.onlookup(req);
4457
+ return true;
4458
+ case COMMANDS.ANNOUNCE:
4459
+ this._persistent.onannounce(req);
4460
+ return true;
4461
+ case COMMANDS.UNANNOUNCE:
4462
+ this._persistent.onunannounce(req);
4463
+ return true;
4464
+ case COMMANDS.MUTABLE_PUT:
4465
+ this._persistent.onmutableput(req);
4466
+ return true;
4467
+ case COMMANDS.MUTABLE_GET:
4468
+ this._persistent.onmutableget(req);
4469
+ return true;
4470
+ case COMMANDS.IMMUTABLE_PUT:
4471
+ this._persistent.onimmutableput(req);
4472
+ return true;
4473
+ case COMMANDS.IMMUTABLE_GET:
4474
+ this._persistent.onimmutableget(req);
4475
+ return true;
4476
+ case COMMANDS.PLUGIN:
4477
+ this._persistent.onplugin(req);
4478
+ return true;
4479
+ }
4480
+ return false;
4481
+ }
4482
+ static keyPair(seed) {
4483
+ return createKeyPair(seed);
4484
+ }
4485
+ static hash(data) {
4486
+ return hash(data);
4487
+ }
4488
+ static connectRawStream(encryptedStream, rawStream, remoteId) {
4489
+ const stream = encryptedStream.rawStream;
4490
+ if (!stream.connected) throw STREAM_NOT_CONNECTED();
4491
+ rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost);
4492
+ }
4493
+ createRawStream(opts) {
4494
+ return this.rawStreams.add(opts);
4495
+ }
4496
+ async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
4497
+ const ann = {
4498
+ peer: {
4499
+ publicKey: keyPair.publicKey,
4500
+ relayAddresses: relayAddresses || []
4501
+ },
4502
+ refresh: null,
4503
+ signature: null,
4504
+ bump
4505
+ };
4506
+ ann.signature = await sign(target, token, from.id, ann, keyPair);
4507
+ const value = c.encode(m.announce, ann);
4508
+ return dht.request({
4509
+ token,
4510
+ target,
4511
+ command: COMMANDS.ANNOUNCE,
4512
+ value
4513
+ }, from);
4514
+ }
4515
+ async _requestUnannounce(keyPair, dht, target, token, from, sign) {
4516
+ const unann = {
4517
+ peer: {
4518
+ publicKey: keyPair.publicKey,
4519
+ relayAddresses: []
4520
+ },
4521
+ signature: null
4522
+ };
4523
+ unann.signature = await sign(target, token, from.id, unann, keyPair);
4524
+ const value = c.encode(m.announce, unann);
4525
+ return dht.request({
4526
+ token,
4527
+ target,
4528
+ command: COMMANDS.UNANNOUNCE,
4529
+ value
4530
+ }, from);
4531
+ }
4532
+ register(name, plugin) {
4533
+ this.plugins.set(name, plugin);
4534
+ plugin.onregister(this);
4535
+ }
4536
+ };
4537
+ HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES;
4538
+ HyperDHT.FIREWALL = FIREWALL;
4539
+ module.exports = HyperDHT;
4540
+ function mapLookup(node) {
4541
+ if (!node.value) return null;
4542
+ try {
4543
+ const l = c.decode(m.lookupRawReply, node.value);
4544
+ return {
4545
+ token: node.token,
4546
+ from: node.from,
4547
+ to: node.to,
4548
+ peers: l.peers,
4549
+ bump: l.bump
4550
+ };
4551
+ } catch {
4552
+ return null;
4553
+ }
4554
+ }
4555
+ function mapFindPeer(node) {
4556
+ if (!node.value) return null;
4557
+ try {
4558
+ return {
4559
+ token: node.token,
4560
+ from: node.from,
4561
+ to: node.to,
4562
+ peer: c.decode(m.peer, node.value)
4563
+ };
4564
+ } catch {
4565
+ return null;
4566
+ }
4567
+ }
4568
+ function mapImmutable(node) {
4569
+ if (!node.value) return null;
4570
+ return {
4571
+ token: node.token,
4572
+ from: node.from,
4573
+ to: node.to,
4574
+ value: node.value
4575
+ };
4576
+ }
4577
+ function mapMutable(node) {
4578
+ if (!node.value) return null;
4579
+ try {
4580
+ const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value);
4581
+ return {
4582
+ token: node.token,
4583
+ from: node.from,
4584
+ to: node.to,
4585
+ seq,
4586
+ value,
4587
+ signature
4588
+ };
4589
+ } catch {
4590
+ return null;
4591
+ }
4592
+ }
4593
+ function noop() {}
4594
+ function filterNode(node) {
4595
+ return !(node.port === 49738 && (node.host === "134.209.28.98" || node.host === "167.99.142.185")) && !(node.port === 9400 && node.host === "35.233.47.252") && !(node.host === "150.136.142.116");
4596
+ }
4597
+ var defaultMaxSize = 65536;
4598
+ var defaultMaxAge = 12e5;
4599
+ function defaultCacheOpts(opts) {
4600
+ const maxSize = opts.maxSize || defaultMaxSize;
4601
+ const maxAge = opts.maxAge || defaultMaxAge;
4602
+ return {
4603
+ router: { forwards: {
4604
+ maxSize,
4605
+ maxAge
4606
+ } },
4607
+ relayAddresses: {
4608
+ maxSize: Math.min(maxSize, 512),
4609
+ maxAge: 0
4610
+ },
4611
+ persistent: {
4612
+ records: {
4613
+ maxSize,
4614
+ maxAge
4615
+ },
4616
+ refreshes: {
4617
+ maxSize,
4618
+ maxAge
4619
+ },
4620
+ mutables: {
4621
+ maxSize: maxSize / 2 | 0,
4622
+ maxAge: opts.maxAge || 1728e5
4623
+ },
4624
+ immutables: {
4625
+ maxSize: maxSize / 2 | 0,
4626
+ maxAge: opts.maxAge || 1728e5
4627
+ },
4628
+ bumps: {
4629
+ maxSize,
4630
+ maxAge
4631
+ }
4632
+ }
4633
+ };
4634
+ }
4635
+ })))(), 1);
4636
+ /**
4637
+ * How long a HyperDHT dial whose stream opened may go without the contact's preface before it is dialled again.
4638
+ *
4639
+ * The first connection a freshly started process makes sometimes opens (the handshake went through the DHT and the
4640
+ * stream is connected to the right address) and then carries nothing: the contact never sees it, and UDX gives up
4641
+ * only after 13 s. A connection made again at once goes through in milliseconds. Found as a chat moved to HyperDHT
4642
+ * right after the contact's app restarted taking about 28 s in CI (the move's 8 s, then its 20 s retry), 1 run in 6;
4643
+ * reproduced with hyperdht alone under load (bug hunt r11h). On loopback the preface comes within milliseconds of
4644
+ * the stream opening, one round trip on the internet.
4645
+ */
4646
+ var PREFACE_WAIT_MS = 2e3;
4647
+ /**
4648
+ * The longest a stream that opened waits for the preface on a slow path: the 8 s a chat's move gives its dial. Past
4649
+ * it nobody is waiting for the dial made again, and UDX gives a silent stream up at 13 s anyway.
4650
+ */
4651
+ var PREFACE_MAX_WAIT_MS = 8e3;
4652
+ /**
4653
+ * The preface wait for a stream whose smoothed RTT is `rtt` ms and whose dial took `opening` ms to open: three round
4654
+ * trips once there is a sample, the opening itself before, between `floor` and `ceiling`.
4655
+ */
4656
+ function prefaceWait(rtt, opening = 0, floor = PREFACE_WAIT_MS, ceiling = PREFACE_MAX_WAIT_MS) {
4657
+ const wait = rtt > 0 ? 3 * rtt : 1 * (opening || 0);
4658
+ return Math.min(ceiling, Math.max(floor, wait));
4659
+ }
4660
+ /**
4661
+ * Dials with `dialOnce` until one brings the contact's preface. `dialOnce()` starts a connection and returns
4662
+ * `{ opened, ready, close }`: `opened` resolves true once the stream is open (the handshake is done), `ready` with the
4663
+ * bound channel once the contact's preface came, and `close()` drops it; `rtt()`, if given, is the stream's smoothed
4664
+ * RTT in ms so far, 0 before its first sample (UDX's `rawStream.rtt`). A dial that opened and brought no preface
4665
+ * within `waitMs`, or longer on a slow path (`prefaceWait`, at most `maxWaitMs`), is closed and made again, up to
4666
+ * `maxDials` in all. The RTT is read again whenever the wait would end, so a sample taken after the stream opened
4667
+ * counts. A dial that fails before it opened (the contact not found, refused) fails the whole connect at once, as
4668
+ * before: there is nothing to wait for.
4669
+ */
4670
+ function redial(dialOnce, { waitMs = PREFACE_WAIT_MS, maxWaitMs = PREFACE_MAX_WAIT_MS, maxDials = 3 } = {}) {
4671
+ return new Promise((resolve, reject) => {
4672
+ let settled = false;
4673
+ let dials = 0;
4674
+ const attempt = () => {
4675
+ dials++;
4676
+ const dialledAt = Date.now();
4677
+ const dial = dialOnce();
4678
+ let timer = null;
4679
+ let stalled = false;
4680
+ dial.opened.then((open) => {
4681
+ if (!open || settled) return;
4682
+ const openedAt = Date.now();
4683
+ const check = () => {
4684
+ if (settled) return;
4685
+ const left = openedAt + prefaceWait(dial.rtt?.(), openedAt - dialledAt, waitMs, maxWaitMs) - Date.now();
4686
+ if (left > 0) {
4687
+ timer = setTimeout(check, left);
4688
+ return;
4689
+ }
4690
+ if (dials >= maxDials) return;
4691
+ stalled = true;
4692
+ dial.close();
4693
+ attempt();
4694
+ };
4695
+ timer = setTimeout(check, waitMs);
4696
+ }, () => {});
4697
+ dial.ready.then((bound) => {
4698
+ clearTimeout(timer);
4699
+ if (settled || stalled) {
4700
+ bound.channel.close();
4701
+ return;
4702
+ }
4703
+ settled = true;
4704
+ resolve(bound);
4705
+ }, (error) => {
4706
+ clearTimeout(timer);
4707
+ if (settled || stalled) return;
4708
+ settled = true;
4709
+ reject(error);
4710
+ });
4711
+ };
4712
+ attempt();
4713
+ });
4714
+ }
4715
+ //#endregion
4716
+ //#region ../../native/transports/hyperdht/endpoint.mjs
4717
+ var MAX_FRAME = 61440;
4718
+ /** The top bit of a frame's length word: the frame is a binary message, not UTF-8 text (WISP 103). */
4719
+ var BINARY = 2147483648;
4720
+ var PREFACE = "ghostly/paired-chat/1";
4721
+ /** How long a closing channel waits for what it sent last to go out before the stream is destroyed anyway. */
4722
+ var CLOSE_FLUSH_MS = 300;
4723
+ /**
4724
+ * Bytes a channel may hold before `send` throws: above what every sender here lets itself queue (the CLI's 1 MiB high
4725
+ * water mark and an app's quarter above it; the Desktop page, which stops a file once the sidecar says `full` past its
4726
+ * `SEND_ROOM`), so it trips only for one that ignores its own line.
4727
+ */
4728
+ var MAX_BUFFERED = 2097152;
4729
+ /**
4730
+ * `drained()` resolves once a channel holds no more than this: no more than the sidecar's `SEND_ROOM`, so its wait for
4731
+ * room never spins on a `drained()` that resolves at once.
4732
+ */
4733
+ var DRAINED_AT = 65536;
4734
+ /**
4735
+ * How often a wait in `drained()` looks again. Each stream says `drain` only once its own queue is empty, which on a fast
4736
+ * link comes first; on a slow one this finds the queue at `DRAINED_AT` before it runs dry.
4737
+ */
4738
+ var DRAIN_POLL_MS = 10;
4739
+ /**
4740
+ * What a connection's stream still holds: secret-stream's queue and the UDX stream's under it. Both are streamx
4741
+ * streams, which count it in `_writableState.buffered` (hyperdht is pinned; hyperdhtEndpointBuffered.test.ts reads it).
4742
+ * secret-stream has no `writableLength`: read from there, it was always 0.
4743
+ */
4744
+ function held(socket) {
4745
+ return (socket._writableState?.buffered ?? 0) + (socket.rawStream?._writableState?.buffered ?? 0);
4746
+ }
4747
+ /**
4748
+ * The DHT nodes of this process, by network: every chat's endpoint listens and dials on its network's one node, each
4749
+ * with its own key pair. A node per chat was a UDP socket, a routing table and dht-rpc's table pings per chat, on top
4750
+ * of each listener's announce keepalive; eight chats were eight of each. A node goes once its last endpoint closed.
4751
+ */
4752
+ var nodes = /* @__PURE__ */ new Map();
4753
+ function shareNode(options) {
4754
+ const key = JSON.stringify([
4755
+ options.bootstrap ?? null,
4756
+ options.host ?? null,
4757
+ options.port ?? null
4758
+ ]);
4759
+ let shared = nodes.get(key);
4760
+ if (!shared) nodes.set(key, shared = {
4761
+ node: new import_hyperdht.default({
4762
+ ...options,
4763
+ ephemeral: true
4764
+ }),
4765
+ users: 0,
4766
+ closing: /* @__PURE__ */ new Map()
4767
+ });
4768
+ shared.users++;
4769
+ let released = false;
4770
+ return {
4771
+ node: shared.node,
4772
+ closing: shared.closing,
4773
+ async release() {
4774
+ if (released) return;
4775
+ released = true;
4776
+ if (--shared.users > 0) return;
4777
+ if (nodes.get(key) === shared) nodes.delete(key);
4778
+ await shared.node.destroy();
4779
+ }
4780
+ };
4781
+ }
4782
+ /**
4783
+ * Stops or starts the announcing of a listener: its record on three DHT nodes, and the ping to each of them every 3 s
4784
+ * that keeps it reachable there (hyperdht's announcer, `lib/announcer.js`; hyperdht is pinned, and
4785
+ * hyperdhtEndpointShared.test.ts reads it). Only the announcer: `server.suspend()` would also end the handshakes it
4786
+ * holds, which for 10 s after a connection opened include that connection's stream. While stopped, the server still
4787
+ * answers a handshake that reaches it, and its connections go on.
4788
+ */
4789
+ function announcing(server, on) {
4790
+ const announcer = server._announcer;
4791
+ if (!announcer) return;
4792
+ if (on) announcer.resume();
4793
+ else announcer.suspend().catch(() => {});
4794
+ }
4795
+ /** Native UDP + NoiseSecretStream. The binding comes from the authenticated
4796
+ * stream itself, never from an application frame supplied by the other peer.
4797
+ *
4798
+ * The listener is announced only while no channel is live: with one, the contact already reached this chat, and it is
4799
+ * announced again as soon as the last one closes. A contact whose side lost the session first (its network changed,
4800
+ * its app was killed) can dial again only once this side's session ends too (its liveness, about a minute); this side
4801
+ * dials it meanwhile as well. */
4802
+ async function createHyperEndpoint(seed, options = {}) {
4803
+ if (!(seed instanceof Uint8Array) || seed.length !== 32) throw new Error("Invalid HyperDHT seed");
4804
+ const keyPair = import_hyperdht.default.keyPair(Buffer.from(seed));
4805
+ const hex = keyPair.publicKey.toString("hex");
4806
+ const shared = shareNode(options);
4807
+ const node = shared.node;
4808
+ await shared.closing.get(hex)?.catch(() => {});
4809
+ const channels = /* @__PURE__ */ new Set();
4810
+ /** The channels whose contact's preface came: the chat is live on them. */
4811
+ const live = /* @__PURE__ */ new Set();
4812
+ /** Every stream this endpoint dialled that is not closed yet: the node stays when the endpoint closes, they do not. */
4813
+ const dialled = /* @__PURE__ */ new Set();
4814
+ let quiet = false;
4815
+ let stopped = false;
4816
+ let closing = null;
4817
+ let incomingHandler = null;
4818
+ const waiting = [];
4819
+ const descriptor = { publicKey: hex };
4820
+ let server = null;
4821
+ let listening = false;
4822
+ function liveChanged() {
4823
+ const want = !stopped && live.size > 0;
4824
+ if (want === quiet || !listening) return;
4825
+ quiet = want;
4826
+ announcing(server, !want);
4827
+ }
4828
+ /** `onChannel`: hears the channel as soon as it counts against the limit (a dial that stalls is dropped from it). */
4829
+ async function attach(socket, onChannel) {
4830
+ if (stopped || channels.size >= 2) {
4831
+ socket.destroy();
4832
+ throw new Error("Native connection limit reached");
4833
+ }
4834
+ let reader = null;
4835
+ let closeHandler = null;
4836
+ let closed = false;
4837
+ let ending = null;
4838
+ let pending = [];
4839
+ let buffer = Buffer.alloc(0);
4840
+ let preface = false;
4841
+ let resolveOpen, rejectOpen;
4842
+ const ready = new Promise((resolve, reject) => {
4843
+ resolveOpen = resolve;
4844
+ rejectOpen = reject;
4845
+ });
4846
+ const timer = setTimeout(() => {
4847
+ socket.destroy(/* @__PURE__ */ new Error("HyperDHT handshake timed out"));
4848
+ }, 2e4);
4849
+ const channel = {
4850
+ binary: true,
4851
+ get bufferedAmount() {
4852
+ return held(socket);
4853
+ },
4854
+ get onMessage() {
4855
+ return reader;
4856
+ },
4857
+ set onMessage(value) {
4858
+ reader = value;
4859
+ if (value) for (const text of pending.splice(0)) value(text);
4860
+ },
4861
+ get onClose() {
4862
+ return closeHandler;
4863
+ },
4864
+ set onClose(value) {
4865
+ closeHandler = value;
4866
+ if (closed) value?.();
4867
+ },
4868
+ send(data) {
4869
+ const binary = data instanceof Uint8Array;
4870
+ if (closed || !(binary || typeof data === "string") || !data.length || (binary ? data.length : Buffer.byteLength(data)) > 61440 || this.bufferedAmount > MAX_BUFFERED) throw new Error("Native channel is closed or exceeds its frame budget");
4871
+ const payload = binary ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : Buffer.from(data);
4872
+ const header = Buffer.alloc(4);
4873
+ header.writeUInt32BE((binary ? BINARY : 0) + payload.length);
4874
+ socket.write(Buffer.concat([header, payload]));
4875
+ },
4876
+ drained() {
4877
+ if (this.bufferedAmount <= DRAINED_AT) return Promise.resolve();
4878
+ if (closed) return Promise.reject(/* @__PURE__ */ new Error("Native channel closed"));
4879
+ return new Promise((resolve, reject) => {
4880
+ const raw = socket.rawStream;
4881
+ const check = () => {
4882
+ if (this.bufferedAmount <= DRAINED_AT) finish(resolve);
4883
+ };
4884
+ const gone = () => finish(() => reject(/* @__PURE__ */ new Error("Native channel closed")));
4885
+ const poll = setInterval(check, DRAIN_POLL_MS);
4886
+ poll.unref?.();
4887
+ function finish(settle) {
4888
+ clearInterval(poll);
4889
+ socket.off("drain", check);
4890
+ raw?.off("drain", check);
4891
+ socket.off("close", gone);
4892
+ settle();
4893
+ }
4894
+ socket.on("drain", check);
4895
+ raw?.on("drain", check);
4896
+ socket.once("close", gone);
4897
+ });
4898
+ },
4899
+ close() {
4900
+ if (closed || ending) return ending ?? Promise.resolve();
4901
+ ending = new Promise((resolve) => {
4902
+ socket.once("close", resolve);
4903
+ });
4904
+ setTimeout(() => socket.destroy(), CLOSE_FLUSH_MS).unref?.();
4905
+ socket.end();
4906
+ return ending;
4907
+ }
4908
+ };
4909
+ channels.add(channel);
4910
+ onChannel?.(channel);
4911
+ socket.on("error", (error) => rejectOpen(error));
4912
+ socket.on("end", () => socket.end());
4913
+ socket.on("close", () => {
4914
+ closed = true;
4915
+ pending = [];
4916
+ clearTimeout(timer);
4917
+ channels.delete(channel);
4918
+ if (live.delete(channel)) liveChanged();
4919
+ rejectOpen(/* @__PURE__ */ new Error("Native channel closed"));
4920
+ closeHandler?.();
4921
+ });
4922
+ const opened = () => {
4923
+ if (socket.handshakeHash?.length !== 64 || socket.publicKey?.length !== 32 || socket.remotePublicKey?.length !== 32) {
4924
+ socket.destroy(/* @__PURE__ */ new Error("Noise session binding unavailable"));
4925
+ return;
4926
+ }
4927
+ channel.send(PREFACE);
4928
+ };
4929
+ socket.on("data", (chunk) => {
4930
+ buffer = Buffer.concat([buffer, chunk]);
4931
+ while (buffer.length >= 4) {
4932
+ const word = buffer.readUInt32BE(0);
4933
+ const binary = word >= BINARY, length = word % BINARY;
4934
+ if (length === 0 || length > 61440 || binary && !preface) {
4935
+ socket.destroy(/* @__PURE__ */ new Error("Invalid frame length"));
4936
+ return;
4937
+ }
4938
+ if (buffer.length < 4 + length) break;
4939
+ let text;
4940
+ if (binary) text = new Uint8Array(buffer.subarray(4, 4 + length));
4941
+ else try {
4942
+ text = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(4, 4 + length));
4943
+ } catch {
4944
+ socket.destroy(/* @__PURE__ */ new Error("Invalid UTF-8 frame"));
4945
+ return;
4946
+ }
4947
+ buffer = buffer.subarray(4 + length);
4948
+ if (!preface) {
4949
+ if (text !== PREFACE) {
4950
+ socket.destroy(/* @__PURE__ */ new Error("Unexpected application protocol"));
4951
+ return;
4952
+ }
4953
+ preface = true;
4954
+ clearTimeout(timer);
4955
+ live.add(channel);
4956
+ liveChanged();
4957
+ resolveOpen({
4958
+ channel,
4959
+ binding: {
4960
+ transport: "hyperdht/1",
4961
+ context: socket.handshakeHash.toString("hex"),
4962
+ identities: [socket.publicKey.toString("hex"), socket.remotePublicKey.toString("hex")].sort()
4963
+ }
4964
+ });
4965
+ } else if (reader) reader(text);
4966
+ else if (pending.length < 64) pending.push(text);
4967
+ else {
4968
+ socket.destroy(/* @__PURE__ */ new Error("Receive queue exceeded"));
4969
+ return;
4970
+ }
4971
+ }
4972
+ });
4973
+ socket.opened.then((ok) => {
4974
+ if (ok) opened();
4975
+ else rejectOpen(/* @__PURE__ */ new Error("Noise handshake failed"));
4976
+ });
4977
+ return ready;
4978
+ }
4979
+ server = node.createServer((socket) => {
4980
+ attach(socket).then((bound) => {
4981
+ if (stopped) bound.channel.close();
4982
+ else if (incomingHandler) incomingHandler(bound);
4983
+ else waiting.push(bound);
4984
+ }).catch(() => {});
4985
+ });
4986
+ try {
4987
+ await server.listen(keyPair);
4988
+ } catch (error) {
4989
+ await server.close().catch(() => {});
4990
+ await shared.release();
4991
+ throw error;
4992
+ }
4993
+ listening = true;
4994
+ liveChanged();
4995
+ return {
4996
+ transport: "hyperdht/1",
4997
+ descriptor,
4998
+ onDescriptor: null,
4999
+ get onConnection() {
5000
+ return incomingHandler;
5001
+ },
5002
+ set onConnection(value) {
5003
+ incomingHandler = value;
5004
+ if (value) for (const bound of waiting.splice(0)) value(bound);
5005
+ },
5006
+ async connect(address) {
5007
+ if (stopped || !address || !/^[a-f0-9]{64}$/.test(address.publicKey)) throw new Error("Invalid HyperDHT endpoint");
5008
+ const remote = Buffer.from(address.publicKey, "hex");
5009
+ return redial(() => {
5010
+ const socket = node.connect(remote, { keyPair });
5011
+ dialled.add(socket);
5012
+ socket.once("close", () => dialled.delete(socket));
5013
+ if (stopped) socket.destroy();
5014
+ let counted = null;
5015
+ const ready = attach(socket, (channel) => {
5016
+ counted = channel;
5017
+ });
5018
+ return {
5019
+ opened: socket.opened,
5020
+ ready,
5021
+ rtt: () => socket.rawStream?.rtt ?? 0,
5022
+ close() {
5023
+ if (counted) channels.delete(counted);
5024
+ socket.destroy();
5025
+ }
5026
+ };
5027
+ });
5028
+ },
5029
+ close() {
5030
+ if (closing) return closing;
5031
+ stopped = true;
5032
+ closing = (async () => {
5033
+ const ended = [...channels].map((channel) => channel.close());
5034
+ waiting.length = 0;
5035
+ await Promise.all(ended);
5036
+ for (const socket of dialled) socket.destroy();
5037
+ await server.close();
5038
+ await shared.release();
5039
+ })();
5040
+ const done = closing.finally(() => {
5041
+ if (shared.closing.get(hex) === done) shared.closing.delete(hex);
5042
+ });
5043
+ done.catch(() => {});
5044
+ shared.closing.set(hex, done);
5045
+ return closing;
5046
+ }
5047
+ };
5048
+ }
5049
+ //#endregion
5050
+ export { MAX_FRAME, createHyperEndpoint };
5051
+
5052
+ //# sourceMappingURL=endpoint-DarqblYE.js.map