@highway1/core 0.1.46 → 0.1.48
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.
- package/dist/index.d.ts +308 -1
- package/dist/index.js +3430 -85
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +5 -0
- package/src/messaging/defense.ts +236 -0
- package/src/messaging/index.ts +5 -0
- package/src/messaging/queue.ts +181 -0
- package/src/messaging/rate-limiter.ts +85 -0
- package/src/messaging/router.ts +38 -7
- package/src/messaging/storage.ts +281 -0
- package/src/messaging/types.ts +149 -0
- package/src/transport/node.ts +3 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
|
+
import 'path';
|
|
2
|
+
import 'url';
|
|
1
3
|
import * as ed25519 from '@noble/ed25519';
|
|
2
4
|
import { base58btc } from 'multiformats/bases/base58';
|
|
3
5
|
import { createLibp2p } from 'libp2p';
|
|
4
6
|
import { tcp } from '@libp2p/tcp';
|
|
7
|
+
import { setMaxListeners as setMaxListeners$1 } from 'events';
|
|
8
|
+
import { CODE_IP6, CODE_IP4, CODE_P2P, CODE_QUIC_V1, CODE_QUIC, CODE_UDP, CODE_TCP, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_DNS, CODE_IPCIDR, CODE_IP6ZONE, CODE_WS, CODE_SNI, CODE_TLS, CODE_WSS, CODE_CERTHASH, CODE_WEBRTC_DIRECT, CODE_WEBTRANSPORT, CODE_P2P_CIRCUIT, CODE_WEBRTC, CODE_HTTP, CODE_HTTPS, CODE_MEMORY, CODE_UNIX, multiaddr } from '@multiformats/multiaddr';
|
|
9
|
+
import http from 'http';
|
|
10
|
+
import https from 'https';
|
|
11
|
+
import net, { isIPv4, isIPv6 } from 'net';
|
|
12
|
+
import { allocUnsafe, alloc } from 'uint8arrays/alloc';
|
|
13
|
+
import { concat } from 'uint8arrays/concat';
|
|
14
|
+
import { equals } from 'uint8arrays/equals';
|
|
15
|
+
import os from 'os';
|
|
16
|
+
import * as ws from 'ws';
|
|
17
|
+
import { fromString } from 'uint8arrays/from-string';
|
|
5
18
|
import { noise } from '@chainsafe/libp2p-noise';
|
|
6
19
|
import { mplex } from '@libp2p/mplex';
|
|
7
20
|
import { kadDHT, passthroughMapper } from '@libp2p/kad-dht';
|
|
@@ -11,23 +24,35 @@ import { ping } from '@libp2p/ping';
|
|
|
11
24
|
import { circuitRelayTransport, circuitRelayServer } from '@libp2p/circuit-relay-v2';
|
|
12
25
|
import Ajv from 'ajv';
|
|
13
26
|
import { encode, decode } from 'cbor-x';
|
|
14
|
-
import { fromString } from 'uint8arrays/from-string';
|
|
15
27
|
import { toString } from 'uint8arrays/to-string';
|
|
16
28
|
import lunr from 'lunr';
|
|
17
29
|
import Fuse from 'fuse.js';
|
|
18
30
|
import { peerIdFromString } from '@libp2p/peer-id';
|
|
19
|
-
import { multiaddr } from '@multiformats/multiaddr';
|
|
20
31
|
import { Level } from 'level';
|
|
21
32
|
import { sha256 } from '@noble/hashes/sha256';
|
|
22
33
|
import { bytesToHex } from '@noble/hashes/utils';
|
|
23
34
|
|
|
35
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
36
|
+
var __esm = (fn, res) => function __init() {
|
|
37
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
38
|
+
};
|
|
39
|
+
var init_esm_shims = __esm({
|
|
40
|
+
"../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js"() {
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// src/index.ts
|
|
45
|
+
init_esm_shims();
|
|
46
|
+
|
|
24
47
|
// src/identity/keys.ts
|
|
48
|
+
init_esm_shims();
|
|
25
49
|
|
|
26
50
|
// src/utils/errors.ts
|
|
51
|
+
init_esm_shims();
|
|
27
52
|
var ClawiverseError = class extends Error {
|
|
28
|
-
constructor(message,
|
|
53
|
+
constructor(message, code2, details) {
|
|
29
54
|
super(message);
|
|
30
|
-
this.code =
|
|
55
|
+
this.code = code2;
|
|
31
56
|
this.details = details;
|
|
32
57
|
this.name = "ClawiverseError";
|
|
33
58
|
}
|
|
@@ -96,6 +121,9 @@ function importKeyPair(exported) {
|
|
|
96
121
|
privateKey: new Uint8Array(Buffer.from(exported.privateKey, "hex"))
|
|
97
122
|
};
|
|
98
123
|
}
|
|
124
|
+
|
|
125
|
+
// src/identity/did.ts
|
|
126
|
+
init_esm_shims();
|
|
99
127
|
function deriveDID(publicKey) {
|
|
100
128
|
try {
|
|
101
129
|
const encoded = base58btc.encode(publicKey);
|
|
@@ -114,51 +142,2721 @@ function extractPublicKey(did) {
|
|
|
114
142
|
} catch (error) {
|
|
115
143
|
throw new IdentityError("Failed to extract public key from DID", error);
|
|
116
144
|
}
|
|
117
|
-
}
|
|
118
|
-
function validateDID(did) {
|
|
119
|
-
if (!did.startsWith("did:clawiverse:")) {
|
|
120
|
-
return false;
|
|
145
|
+
}
|
|
146
|
+
function validateDID(did) {
|
|
147
|
+
if (!did.startsWith("did:clawiverse:")) {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
const encoded = did.replace("did:clawiverse:", "");
|
|
152
|
+
base58btc.decode(encoded);
|
|
153
|
+
return true;
|
|
154
|
+
} catch {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/identity/signer.ts
|
|
160
|
+
init_esm_shims();
|
|
161
|
+
async function signMessage(payload, privateKey, publicKey) {
|
|
162
|
+
try {
|
|
163
|
+
const signature = await sign(payload, privateKey);
|
|
164
|
+
const signer = deriveDID(publicKey);
|
|
165
|
+
return {
|
|
166
|
+
payload,
|
|
167
|
+
signature,
|
|
168
|
+
signer
|
|
169
|
+
};
|
|
170
|
+
} catch (error) {
|
|
171
|
+
throw new IdentityError("Failed to sign message", error);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
async function verifyMessage(signedMessage, expectedPublicKey) {
|
|
175
|
+
try {
|
|
176
|
+
const expectedDID = deriveDID(expectedPublicKey);
|
|
177
|
+
if (signedMessage.signer !== expectedDID) {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
return await verify(
|
|
181
|
+
signedMessage.signature,
|
|
182
|
+
signedMessage.payload,
|
|
183
|
+
expectedPublicKey
|
|
184
|
+
);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw new IdentityError("Failed to verify message", error);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/transport/node.ts
|
|
191
|
+
init_esm_shims();
|
|
192
|
+
|
|
193
|
+
// ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/index.js
|
|
194
|
+
init_esm_shims();
|
|
195
|
+
|
|
196
|
+
// ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/index.js
|
|
197
|
+
init_esm_shims();
|
|
198
|
+
|
|
199
|
+
// ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/errors.js
|
|
200
|
+
init_esm_shims();
|
|
201
|
+
var InvalidParametersError = class extends Error {
|
|
202
|
+
static name = "InvalidParametersError";
|
|
203
|
+
constructor(message = "Invalid parameters") {
|
|
204
|
+
super(message);
|
|
205
|
+
this.name = "InvalidParametersError";
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
var ConnectionFailedError = class extends Error {
|
|
209
|
+
static name = "ConnectionFailedError";
|
|
210
|
+
constructor(message = "Connection failed") {
|
|
211
|
+
super(message);
|
|
212
|
+
this.name = "ConnectionFailedError";
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
var StreamResetError = class extends Error {
|
|
216
|
+
static name = "StreamResetError";
|
|
217
|
+
constructor(message = "The stream has been reset") {
|
|
218
|
+
super(message);
|
|
219
|
+
this.name = "StreamResetError";
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
var StreamStateError = class extends Error {
|
|
223
|
+
static name = "StreamStateError";
|
|
224
|
+
constructor(message = "The stream is in an invalid state") {
|
|
225
|
+
super(message);
|
|
226
|
+
this.name = "StreamStateError";
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
var StreamBufferError = class extends Error {
|
|
230
|
+
static name = "StreamBufferError";
|
|
231
|
+
constructor(message = "The stream buffer was full") {
|
|
232
|
+
super(message);
|
|
233
|
+
this.name = "StreamBufferError";
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
// ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/events.js
|
|
238
|
+
init_esm_shims();
|
|
239
|
+
var StreamMessageEvent = class extends Event {
|
|
240
|
+
data;
|
|
241
|
+
constructor(data, eventInitDict) {
|
|
242
|
+
super("message", eventInitDict);
|
|
243
|
+
this.data = data;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
var StreamCloseEvent = class extends Event {
|
|
247
|
+
error;
|
|
248
|
+
local;
|
|
249
|
+
constructor(local, error, eventInitDict) {
|
|
250
|
+
super("close", eventInitDict);
|
|
251
|
+
this.error = error;
|
|
252
|
+
this.local = local;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
var StreamAbortEvent = class extends StreamCloseEvent {
|
|
256
|
+
constructor(error, eventInitDict) {
|
|
257
|
+
super(true, error, eventInitDict);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
var StreamResetEvent = class extends StreamCloseEvent {
|
|
261
|
+
constructor(error, eventInitDict) {
|
|
262
|
+
super(false, error, eventInitDict);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
// ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/transport.js
|
|
267
|
+
init_esm_shims();
|
|
268
|
+
var transportSymbol = /* @__PURE__ */ Symbol.for("@libp2p/transport");
|
|
269
|
+
var FaultTolerance;
|
|
270
|
+
(function(FaultTolerance2) {
|
|
271
|
+
FaultTolerance2[FaultTolerance2["FATAL_ALL"] = 0] = "FATAL_ALL";
|
|
272
|
+
FaultTolerance2[FaultTolerance2["NO_FATAL"] = 1] = "NO_FATAL";
|
|
273
|
+
})(FaultTolerance || (FaultTolerance = {}));
|
|
274
|
+
|
|
275
|
+
// ../../node_modules/.pnpm/main-event@1.0.1/node_modules/main-event/dist/src/index.js
|
|
276
|
+
init_esm_shims();
|
|
277
|
+
|
|
278
|
+
// ../../node_modules/.pnpm/main-event@1.0.1/node_modules/main-event/dist/src/events.js
|
|
279
|
+
init_esm_shims();
|
|
280
|
+
var setMaxListeners = (n, ...eventTargets) => {
|
|
281
|
+
try {
|
|
282
|
+
setMaxListeners$1(n, ...eventTargets);
|
|
283
|
+
} catch {
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
// ../../node_modules/.pnpm/main-event@1.0.1/node_modules/main-event/dist/src/index.js
|
|
288
|
+
var TypedEventEmitter = class extends EventTarget {
|
|
289
|
+
#listeners = /* @__PURE__ */ new Map();
|
|
290
|
+
constructor() {
|
|
291
|
+
super();
|
|
292
|
+
setMaxListeners(Infinity, this);
|
|
293
|
+
}
|
|
294
|
+
listenerCount(type) {
|
|
295
|
+
const listeners = this.#listeners.get(type);
|
|
296
|
+
if (listeners == null) {
|
|
297
|
+
return 0;
|
|
298
|
+
}
|
|
299
|
+
return listeners.length;
|
|
300
|
+
}
|
|
301
|
+
addEventListener(type, listener, options) {
|
|
302
|
+
super.addEventListener(type, listener, options);
|
|
303
|
+
let list = this.#listeners.get(type);
|
|
304
|
+
if (list == null) {
|
|
305
|
+
list = [];
|
|
306
|
+
this.#listeners.set(type, list);
|
|
307
|
+
}
|
|
308
|
+
list.push({
|
|
309
|
+
callback: listener,
|
|
310
|
+
once: (options !== true && options !== false && options?.once) ?? false
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
removeEventListener(type, listener, options) {
|
|
314
|
+
super.removeEventListener(type.toString(), listener ?? null, options);
|
|
315
|
+
let list = this.#listeners.get(type);
|
|
316
|
+
if (list == null) {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
list = list.filter(({ callback }) => callback !== listener);
|
|
320
|
+
this.#listeners.set(type, list);
|
|
321
|
+
}
|
|
322
|
+
dispatchEvent(event) {
|
|
323
|
+
const result = super.dispatchEvent(event);
|
|
324
|
+
let list = this.#listeners.get(event.type);
|
|
325
|
+
if (list == null) {
|
|
326
|
+
return result;
|
|
327
|
+
}
|
|
328
|
+
list = list.filter(({ once }) => !once);
|
|
329
|
+
this.#listeners.set(event.type, list);
|
|
330
|
+
return result;
|
|
331
|
+
}
|
|
332
|
+
safeDispatchEvent(type, detail = {}) {
|
|
333
|
+
return this.dispatchEvent(new CustomEvent(type, detail));
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
// ../../node_modules/.pnpm/@libp2p+interface@3.1.0/node_modules/@libp2p/interface/dist/src/index.js
|
|
338
|
+
var serviceCapabilities = /* @__PURE__ */ Symbol.for("@libp2p/service-capabilities");
|
|
339
|
+
|
|
340
|
+
// ../../node_modules/.pnpm/@multiformats+multiaddr-matcher@3.0.1/node_modules/@multiformats/multiaddr-matcher/dist/src/index.js
|
|
341
|
+
init_esm_shims();
|
|
342
|
+
|
|
343
|
+
// ../../node_modules/.pnpm/@multiformats+multiaddr-matcher@3.0.1/node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js
|
|
344
|
+
init_esm_shims();
|
|
345
|
+
var code = (code2) => {
|
|
346
|
+
return {
|
|
347
|
+
match: (vals) => {
|
|
348
|
+
const component = vals[0];
|
|
349
|
+
if (component == null) {
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
if (component.code !== code2) {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
if (component.value != null) {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
return vals.slice(1);
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
};
|
|
362
|
+
var value = (code2, value2) => {
|
|
363
|
+
return {
|
|
364
|
+
match: (vals) => {
|
|
365
|
+
const component = vals[0];
|
|
366
|
+
if (component?.code !== code2) {
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
if (component.value == null) {
|
|
370
|
+
return false;
|
|
371
|
+
}
|
|
372
|
+
if (value2 != null && component.value !== value2) {
|
|
373
|
+
return false;
|
|
374
|
+
}
|
|
375
|
+
return vals.slice(1);
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
var not = (matcher) => {
|
|
380
|
+
return {
|
|
381
|
+
match: (vals) => {
|
|
382
|
+
const result = matcher.match(vals);
|
|
383
|
+
if (result === false) {
|
|
384
|
+
return vals;
|
|
385
|
+
}
|
|
386
|
+
return false;
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
var optional = (matcher) => {
|
|
391
|
+
return {
|
|
392
|
+
match: (vals) => {
|
|
393
|
+
const result = matcher.match(vals);
|
|
394
|
+
if (result === false) {
|
|
395
|
+
return vals;
|
|
396
|
+
}
|
|
397
|
+
return result;
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
};
|
|
401
|
+
var or = (...matchers) => {
|
|
402
|
+
return {
|
|
403
|
+
match: (vals) => {
|
|
404
|
+
let matches;
|
|
405
|
+
for (const matcher of matchers) {
|
|
406
|
+
const result = matcher.match(vals);
|
|
407
|
+
if (result === false) {
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
if (matches == null || result.length < matches.length) {
|
|
411
|
+
matches = result;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (matches == null) {
|
|
415
|
+
return false;
|
|
416
|
+
}
|
|
417
|
+
return matches;
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
var and = (...matchers) => {
|
|
422
|
+
return {
|
|
423
|
+
match: (vals) => {
|
|
424
|
+
for (const matcher of matchers) {
|
|
425
|
+
const result = matcher.match(vals);
|
|
426
|
+
if (result === false) {
|
|
427
|
+
return false;
|
|
428
|
+
}
|
|
429
|
+
vals = result;
|
|
430
|
+
}
|
|
431
|
+
return vals;
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
};
|
|
435
|
+
function fmt(...matchers) {
|
|
436
|
+
function match(ma) {
|
|
437
|
+
if (ma == null) {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
let parts = ma.getComponents();
|
|
441
|
+
for (const matcher of matchers) {
|
|
442
|
+
const result = matcher.match(parts);
|
|
443
|
+
if (result === false) {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
parts = result;
|
|
447
|
+
}
|
|
448
|
+
return parts;
|
|
449
|
+
}
|
|
450
|
+
function matches(ma) {
|
|
451
|
+
const result = match(ma);
|
|
452
|
+
return result !== false;
|
|
453
|
+
}
|
|
454
|
+
function exactMatch(ma) {
|
|
455
|
+
const result = match(ma);
|
|
456
|
+
if (result === false) {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
return result.length === 0;
|
|
460
|
+
}
|
|
461
|
+
return {
|
|
462
|
+
matchers,
|
|
463
|
+
matches,
|
|
464
|
+
exactMatch
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ../../node_modules/.pnpm/@multiformats+multiaddr-matcher@3.0.1/node_modules/@multiformats/multiaddr-matcher/dist/src/index.js
|
|
469
|
+
var _PEER_ID = value(CODE_P2P);
|
|
470
|
+
fmt(_PEER_ID);
|
|
471
|
+
var _DNS4 = value(CODE_DNS4);
|
|
472
|
+
var _DNS6 = value(CODE_DNS6);
|
|
473
|
+
var _DNSADDR = value(CODE_DNSADDR);
|
|
474
|
+
var _DNS = value(CODE_DNS);
|
|
475
|
+
fmt(_DNS4, optional(value(CODE_P2P)));
|
|
476
|
+
fmt(_DNS6, optional(value(CODE_P2P)));
|
|
477
|
+
fmt(_DNSADDR, optional(value(CODE_P2P)));
|
|
478
|
+
fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)));
|
|
479
|
+
var _IP4 = and(value(CODE_IP4), optional(value(CODE_IPCIDR)));
|
|
480
|
+
var _IP6 = and(optional(value(CODE_IP6ZONE)), value(CODE_IP6), optional(value(CODE_IPCIDR)));
|
|
481
|
+
var _IP = or(_IP4, _IP6);
|
|
482
|
+
var _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);
|
|
483
|
+
fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))));
|
|
484
|
+
fmt(_IP4);
|
|
485
|
+
fmt(_IP6);
|
|
486
|
+
fmt(_IP);
|
|
487
|
+
var _TCP = and(_IP_OR_DOMAIN, value(CODE_TCP));
|
|
488
|
+
var _UDP = and(_IP_OR_DOMAIN, value(CODE_UDP));
|
|
489
|
+
fmt(and(_TCP, optional(value(CODE_P2P))));
|
|
490
|
+
fmt(_UDP);
|
|
491
|
+
var _QUIC = and(_UDP, code(CODE_QUIC), optional(value(CODE_P2P)));
|
|
492
|
+
var _QUIC_V1 = and(_UDP, code(CODE_QUIC_V1), optional(value(CODE_P2P)));
|
|
493
|
+
var QUIC_V0_OR_V1 = or(_QUIC, _QUIC_V1);
|
|
494
|
+
fmt(_QUIC);
|
|
495
|
+
fmt(_QUIC_V1);
|
|
496
|
+
var _WEB = or(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUIC_V1);
|
|
497
|
+
var _WebSockets = or(and(_WEB, code(CODE_WS), optional(value(CODE_P2P))));
|
|
498
|
+
var WebSockets = fmt(_WebSockets);
|
|
499
|
+
var _WebSocketsSecure = or(and(_WEB, code(CODE_WSS), optional(value(CODE_P2P))), and(_WEB, code(CODE_TLS), optional(value(CODE_SNI)), code(CODE_WS), optional(value(CODE_P2P))));
|
|
500
|
+
var WebSocketsSecure = fmt(_WebSocketsSecure);
|
|
501
|
+
var _WebRTCDirect = and(_UDP, code(CODE_WEBRTC_DIRECT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)));
|
|
502
|
+
fmt(_WebRTCDirect);
|
|
503
|
+
var _WebTransport = and(_QUIC_V1, code(CODE_WEBTRANSPORT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)));
|
|
504
|
+
fmt(_WebTransport);
|
|
505
|
+
var _P2P = or(_WebSockets, _WebSocketsSecure, and(_TCP, optional(value(CODE_P2P))), and(QUIC_V0_OR_V1, optional(value(CODE_P2P))), and(_IP_OR_DOMAIN, optional(value(CODE_P2P))), _WebRTCDirect, _WebTransport, value(CODE_P2P));
|
|
506
|
+
fmt(_P2P);
|
|
507
|
+
var _Circuit = and(optional(_P2P), code(CODE_P2P_CIRCUIT), not(code(CODE_WEBRTC)), optional(value(CODE_P2P)));
|
|
508
|
+
fmt(_Circuit);
|
|
509
|
+
var _WebRTC = or(and(_P2P, code(CODE_P2P_CIRCUIT), code(CODE_WEBRTC), optional(value(CODE_P2P))), and(_P2P, code(CODE_WEBRTC), optional(value(CODE_P2P))), and(code(CODE_WEBRTC), optional(value(CODE_P2P))));
|
|
510
|
+
fmt(_WebRTC);
|
|
511
|
+
var _HTTP = or(and(_IP_OR_DOMAIN, value(CODE_TCP), code(CODE_HTTP), optional(value(CODE_P2P))), and(_IP_OR_DOMAIN, code(CODE_HTTP), optional(value(CODE_P2P))));
|
|
512
|
+
fmt(_HTTP);
|
|
513
|
+
var _HTTPS = and(_IP_OR_DOMAIN, or(and(value(CODE_TCP, "443"), code(CODE_HTTP)), and(value(CODE_TCP), code(CODE_HTTPS)), and(value(CODE_TCP), code(CODE_TLS), code(CODE_HTTP)), and(code(CODE_TLS), code(CODE_HTTP)), code(CODE_TLS), code(CODE_HTTPS)), optional(value(CODE_P2P)));
|
|
514
|
+
fmt(_HTTPS);
|
|
515
|
+
var _Memory = or(and(value(CODE_MEMORY), optional(value(CODE_P2P))));
|
|
516
|
+
fmt(_Memory);
|
|
517
|
+
var _Unix = or(and(value(CODE_UNIX), optional(value(CODE_P2P))));
|
|
518
|
+
fmt(_Unix);
|
|
519
|
+
|
|
520
|
+
// ../../node_modules/.pnpm/@multiformats+multiaddr-to-uri@12.0.0/node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js
|
|
521
|
+
init_esm_shims();
|
|
522
|
+
var ASSUME_HTTP_CODES = [
|
|
523
|
+
CODE_TCP,
|
|
524
|
+
CODE_DNS,
|
|
525
|
+
CODE_DNSADDR,
|
|
526
|
+
CODE_DNS4,
|
|
527
|
+
CODE_DNS6
|
|
528
|
+
];
|
|
529
|
+
function extractSNI(ma) {
|
|
530
|
+
return extractTuple("sni", ma)?.value;
|
|
531
|
+
}
|
|
532
|
+
function extractPort(ma) {
|
|
533
|
+
const port = extractTuple("tcp", ma)?.value;
|
|
534
|
+
if (port == null) {
|
|
535
|
+
return "";
|
|
536
|
+
}
|
|
537
|
+
return `:${port}`;
|
|
538
|
+
}
|
|
539
|
+
function extractTuple(name, ma) {
|
|
540
|
+
return ma.find((component) => component.name === name);
|
|
541
|
+
}
|
|
542
|
+
function hasTLS(ma) {
|
|
543
|
+
return ma.some(({ code: code2 }) => code2 === CODE_TLS);
|
|
544
|
+
}
|
|
545
|
+
function interpretNext(head, rest) {
|
|
546
|
+
const interpreter = interpreters[head.name];
|
|
547
|
+
if (interpreter == null) {
|
|
548
|
+
throw new Error(`Can't interpret protocol ${head.name}`);
|
|
549
|
+
}
|
|
550
|
+
const restVal = interpreter(head, rest);
|
|
551
|
+
if (head.code === CODE_IP6) {
|
|
552
|
+
return `[${restVal}]`;
|
|
553
|
+
}
|
|
554
|
+
return restVal;
|
|
555
|
+
}
|
|
556
|
+
var interpreters = {
|
|
557
|
+
ip4: (head, rest) => head.value,
|
|
558
|
+
ip6: (head, rest) => {
|
|
559
|
+
if (rest.length === 0) {
|
|
560
|
+
return head.value;
|
|
561
|
+
}
|
|
562
|
+
return `[${head.value}]`;
|
|
563
|
+
},
|
|
564
|
+
tcp: (head, rest) => {
|
|
565
|
+
const tail = rest.pop();
|
|
566
|
+
if (tail == null) {
|
|
567
|
+
throw new Error("Unexpected end of multiaddr");
|
|
568
|
+
}
|
|
569
|
+
return `tcp://${interpretNext(tail, rest)}:${head.value}`;
|
|
570
|
+
},
|
|
571
|
+
udp: (head, rest) => {
|
|
572
|
+
const tail = rest.pop();
|
|
573
|
+
if (tail == null) {
|
|
574
|
+
throw new Error("Unexpected end of multiaddr");
|
|
575
|
+
}
|
|
576
|
+
return `udp://${interpretNext(tail, rest)}:${head.value}`;
|
|
577
|
+
},
|
|
578
|
+
dnsaddr: (head, rest) => head.value,
|
|
579
|
+
dns4: (head, rest) => head.value,
|
|
580
|
+
dns6: (head, rest) => head.value,
|
|
581
|
+
dns: (head, rest) => head.value,
|
|
582
|
+
ipfs: (head, rest) => {
|
|
583
|
+
const tail = rest.pop();
|
|
584
|
+
if (tail == null) {
|
|
585
|
+
throw new Error("Unexpected end of multiaddr");
|
|
586
|
+
}
|
|
587
|
+
return `${interpretNext(tail, rest)}`;
|
|
588
|
+
},
|
|
589
|
+
p2p: (head, rest) => {
|
|
590
|
+
const tail = rest.pop();
|
|
591
|
+
if (tail == null) {
|
|
592
|
+
throw new Error("Unexpected end of multiaddr");
|
|
593
|
+
}
|
|
594
|
+
return `${interpretNext(tail, rest)}`;
|
|
595
|
+
},
|
|
596
|
+
http: (head, rest) => {
|
|
597
|
+
const maHasTLS = hasTLS(rest);
|
|
598
|
+
const sni = extractSNI(rest);
|
|
599
|
+
const port = extractPort(rest);
|
|
600
|
+
if (maHasTLS && sni != null) {
|
|
601
|
+
return `https://${sni}${port}`;
|
|
602
|
+
}
|
|
603
|
+
const protocol = maHasTLS ? "https://" : "http://";
|
|
604
|
+
const tail = rest.pop();
|
|
605
|
+
if (tail == null) {
|
|
606
|
+
throw new Error("Unexpected end of multiaddr");
|
|
607
|
+
}
|
|
608
|
+
let baseVal = interpretNext(tail, rest);
|
|
609
|
+
baseVal = baseVal?.replace("tcp://", "");
|
|
610
|
+
return `${protocol}${baseVal}`;
|
|
611
|
+
},
|
|
612
|
+
"http-path": (head, rest) => {
|
|
613
|
+
const tail = rest.pop();
|
|
614
|
+
if (tail == null) {
|
|
615
|
+
throw new Error("Unexpected end of multiaddr");
|
|
616
|
+
}
|
|
617
|
+
const baseVal = interpretNext(tail, rest);
|
|
618
|
+
const decodedValue = decodeURIComponent(head.value ?? "");
|
|
619
|
+
return `${baseVal}${decodedValue}`;
|
|
620
|
+
},
|
|
621
|
+
tls: (head, rest) => {
|
|
622
|
+
const tail = rest.pop();
|
|
623
|
+
if (tail == null) {
|
|
624
|
+
throw new Error("Unexpected end of multiaddr");
|
|
625
|
+
}
|
|
626
|
+
return interpretNext(tail, rest);
|
|
627
|
+
},
|
|
628
|
+
sni: (head, rest) => {
|
|
629
|
+
const tail = rest.pop();
|
|
630
|
+
if (tail == null) {
|
|
631
|
+
throw new Error("Unexpected end of multiaddr");
|
|
632
|
+
}
|
|
633
|
+
return interpretNext(tail, rest);
|
|
634
|
+
},
|
|
635
|
+
https: (head, rest) => {
|
|
636
|
+
const tail = rest.pop();
|
|
637
|
+
if (tail == null) {
|
|
638
|
+
throw new Error("Unexpected end of multiaddr");
|
|
639
|
+
}
|
|
640
|
+
let baseVal = interpretNext(tail, rest);
|
|
641
|
+
baseVal = baseVal?.replace("tcp://", "");
|
|
642
|
+
return `https://${baseVal}`;
|
|
643
|
+
},
|
|
644
|
+
ws: (head, rest) => {
|
|
645
|
+
const maHasTLS = hasTLS(rest);
|
|
646
|
+
const sni = extractSNI(rest);
|
|
647
|
+
const port = extractPort(rest);
|
|
648
|
+
if (maHasTLS && sni != null) {
|
|
649
|
+
return `wss://${sni}${port}`;
|
|
650
|
+
}
|
|
651
|
+
const protocol = maHasTLS ? "wss://" : "ws://";
|
|
652
|
+
const tail = rest.pop();
|
|
653
|
+
if (tail == null) {
|
|
654
|
+
throw new Error("Unexpected end of multiaddr");
|
|
655
|
+
}
|
|
656
|
+
let baseVal = interpretNext(tail, rest);
|
|
657
|
+
baseVal = baseVal?.replace("tcp://", "");
|
|
658
|
+
return `${protocol}${baseVal}`;
|
|
659
|
+
},
|
|
660
|
+
wss: (head, rest) => {
|
|
661
|
+
const tail = rest.pop();
|
|
662
|
+
if (tail == null) {
|
|
663
|
+
throw new Error("Unexpected end of multiaddr");
|
|
664
|
+
}
|
|
665
|
+
let baseVal = interpretNext(tail, rest);
|
|
666
|
+
baseVal = baseVal?.replace("tcp://", "");
|
|
667
|
+
return `wss://${baseVal}`;
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
function multiaddrToUri(input, opts) {
|
|
671
|
+
const ma = multiaddr(input);
|
|
672
|
+
const components = ma.getComponents();
|
|
673
|
+
const head = components.pop();
|
|
674
|
+
if (head == null) {
|
|
675
|
+
throw new Error("Unexpected end of multiaddr");
|
|
676
|
+
}
|
|
677
|
+
const interpreter = interpreters[head.name];
|
|
678
|
+
if (interpreter == null) {
|
|
679
|
+
throw new Error(`No interpreter found for ${head.name}`);
|
|
680
|
+
}
|
|
681
|
+
let uri = interpreter(head, components) ?? "";
|
|
682
|
+
if (ASSUME_HTTP_CODES.includes(head.code)) {
|
|
683
|
+
uri = uri.replace(/^.*:\/\//, "");
|
|
684
|
+
if (head.value === "443") {
|
|
685
|
+
uri = `https://${uri}`;
|
|
686
|
+
} else {
|
|
687
|
+
uri = `http://${uri}`;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("ws://") || uri.startsWith("wss://")) {
|
|
691
|
+
uri = new URL(uri).toString();
|
|
692
|
+
if (uri.endsWith("/")) {
|
|
693
|
+
uri = uri.substring(0, uri.length - 1);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
return uri;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// ../../node_modules/.pnpm/p-event@7.1.0/node_modules/p-event/index.js
|
|
700
|
+
init_esm_shims();
|
|
701
|
+
|
|
702
|
+
// ../../node_modules/.pnpm/p-timeout@7.0.1/node_modules/p-timeout/index.js
|
|
703
|
+
init_esm_shims();
|
|
704
|
+
var TimeoutError = class _TimeoutError extends Error {
|
|
705
|
+
name = "TimeoutError";
|
|
706
|
+
constructor(message, options) {
|
|
707
|
+
super(message, options);
|
|
708
|
+
Error.captureStackTrace?.(this, _TimeoutError);
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
var getAbortedReason = (signal) => signal.reason ?? new DOMException("This operation was aborted.", "AbortError");
|
|
712
|
+
function pTimeout(promise, options) {
|
|
713
|
+
const {
|
|
714
|
+
milliseconds,
|
|
715
|
+
fallback,
|
|
716
|
+
message,
|
|
717
|
+
customTimers = { setTimeout, clearTimeout },
|
|
718
|
+
signal
|
|
719
|
+
} = options;
|
|
720
|
+
let timer;
|
|
721
|
+
let abortHandler;
|
|
722
|
+
const wrappedPromise = new Promise((resolve, reject) => {
|
|
723
|
+
if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
|
|
724
|
+
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
|
|
725
|
+
}
|
|
726
|
+
if (signal?.aborted) {
|
|
727
|
+
reject(getAbortedReason(signal));
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
if (signal) {
|
|
731
|
+
abortHandler = () => {
|
|
732
|
+
reject(getAbortedReason(signal));
|
|
733
|
+
};
|
|
734
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
735
|
+
}
|
|
736
|
+
promise.then(resolve, reject);
|
|
737
|
+
if (milliseconds === Number.POSITIVE_INFINITY) {
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
const timeoutError = new TimeoutError();
|
|
741
|
+
timer = customTimers.setTimeout.call(void 0, () => {
|
|
742
|
+
if (fallback) {
|
|
743
|
+
try {
|
|
744
|
+
resolve(fallback());
|
|
745
|
+
} catch (error) {
|
|
746
|
+
reject(error);
|
|
747
|
+
}
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
if (typeof promise.cancel === "function") {
|
|
751
|
+
promise.cancel();
|
|
752
|
+
}
|
|
753
|
+
if (message === false) {
|
|
754
|
+
resolve();
|
|
755
|
+
} else if (message instanceof Error) {
|
|
756
|
+
reject(message);
|
|
757
|
+
} else {
|
|
758
|
+
timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
|
|
759
|
+
reject(timeoutError);
|
|
760
|
+
}
|
|
761
|
+
}, milliseconds);
|
|
762
|
+
});
|
|
763
|
+
const cancelablePromise = wrappedPromise.finally(() => {
|
|
764
|
+
cancelablePromise.clear();
|
|
765
|
+
if (abortHandler && signal) {
|
|
766
|
+
signal.removeEventListener("abort", abortHandler);
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
cancelablePromise.clear = () => {
|
|
770
|
+
customTimers.clearTimeout.call(void 0, timer);
|
|
771
|
+
timer = void 0;
|
|
772
|
+
};
|
|
773
|
+
return cancelablePromise;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// ../../node_modules/.pnpm/p-event@7.1.0/node_modules/p-event/index.js
|
|
777
|
+
var normalizeEmitter = (emitter) => {
|
|
778
|
+
const addListener = emitter.addEventListener || emitter.on || emitter.addListener;
|
|
779
|
+
const removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;
|
|
780
|
+
if (!addListener || !removeListener) {
|
|
781
|
+
throw new TypeError("Emitter is not compatible");
|
|
782
|
+
}
|
|
783
|
+
return {
|
|
784
|
+
addListener: addListener.bind(emitter),
|
|
785
|
+
removeListener: removeListener.bind(emitter)
|
|
786
|
+
};
|
|
787
|
+
};
|
|
788
|
+
function pEventMultiple(emitter, event, options) {
|
|
789
|
+
let cancel;
|
|
790
|
+
const returnValue = new Promise((resolve, reject) => {
|
|
791
|
+
options = {
|
|
792
|
+
rejectionEvents: ["error"],
|
|
793
|
+
multiArgs: false,
|
|
794
|
+
rejectionMultiArgs: false,
|
|
795
|
+
resolveImmediately: false,
|
|
796
|
+
...options
|
|
797
|
+
};
|
|
798
|
+
if (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {
|
|
799
|
+
throw new TypeError("The `count` option should be at least 0 or more");
|
|
800
|
+
}
|
|
801
|
+
options.signal?.throwIfAborted();
|
|
802
|
+
const events = [event].flat();
|
|
803
|
+
const items = [];
|
|
804
|
+
const { addListener, removeListener } = normalizeEmitter(emitter);
|
|
805
|
+
const onItem = async (...arguments_) => {
|
|
806
|
+
const value2 = options.multiArgs ? arguments_ : arguments_[0];
|
|
807
|
+
if (options.filter) {
|
|
808
|
+
try {
|
|
809
|
+
if (!await options.filter(value2)) {
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
} catch (error) {
|
|
813
|
+
cancel();
|
|
814
|
+
reject(error);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
items.push(value2);
|
|
819
|
+
if (options.count === items.length) {
|
|
820
|
+
cancel();
|
|
821
|
+
resolve(items);
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
const rejectHandler = (...arguments_) => {
|
|
825
|
+
cancel();
|
|
826
|
+
reject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);
|
|
827
|
+
};
|
|
828
|
+
cancel = () => {
|
|
829
|
+
for (const event2 of events) {
|
|
830
|
+
removeListener(event2, onItem);
|
|
831
|
+
}
|
|
832
|
+
for (const rejectionEvent of options.rejectionEvents) {
|
|
833
|
+
if (!events.includes(rejectionEvent)) {
|
|
834
|
+
removeListener(rejectionEvent, rejectHandler);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
for (const event2 of events) {
|
|
839
|
+
addListener(event2, onItem);
|
|
840
|
+
}
|
|
841
|
+
for (const rejectionEvent of options.rejectionEvents) {
|
|
842
|
+
if (!events.includes(rejectionEvent)) {
|
|
843
|
+
addListener(rejectionEvent, rejectHandler);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
if (options.signal) {
|
|
847
|
+
options.signal.addEventListener("abort", () => {
|
|
848
|
+
rejectHandler(options.signal.reason);
|
|
849
|
+
}, { once: true });
|
|
850
|
+
}
|
|
851
|
+
if (options.resolveImmediately) {
|
|
852
|
+
resolve(items);
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
returnValue.cancel = cancel;
|
|
856
|
+
if (typeof options.timeout === "number") {
|
|
857
|
+
const timeout = pTimeout(returnValue, { milliseconds: options.timeout });
|
|
858
|
+
timeout.cancel = () => {
|
|
859
|
+
cancel();
|
|
860
|
+
timeout.clear();
|
|
861
|
+
};
|
|
862
|
+
return timeout;
|
|
863
|
+
}
|
|
864
|
+
return returnValue;
|
|
865
|
+
}
|
|
866
|
+
function pEvent(emitter, event, options) {
|
|
867
|
+
if (typeof options === "function") {
|
|
868
|
+
options = { filter: options };
|
|
869
|
+
}
|
|
870
|
+
options = {
|
|
871
|
+
...options,
|
|
872
|
+
count: 1,
|
|
873
|
+
resolveImmediately: false
|
|
874
|
+
};
|
|
875
|
+
const arrayPromise = pEventMultiple(emitter, event, options);
|
|
876
|
+
const promise = arrayPromise.then((array) => array[0]);
|
|
877
|
+
promise.cancel = arrayPromise.cancel;
|
|
878
|
+
return promise;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// ../../node_modules/.pnpm/progress-events@1.0.1/node_modules/progress-events/dist/src/index.js
|
|
882
|
+
init_esm_shims();
|
|
883
|
+
var CustomProgressEvent = class extends Event {
|
|
884
|
+
type;
|
|
885
|
+
detail;
|
|
886
|
+
constructor(type, detail) {
|
|
887
|
+
super(type);
|
|
888
|
+
this.type = type;
|
|
889
|
+
this.detail = detail;
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
// ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/listener.js
|
|
894
|
+
init_esm_shims();
|
|
895
|
+
|
|
896
|
+
// ../../node_modules/.pnpm/uint8arraylist@2.4.8/node_modules/uint8arraylist/dist/src/index.js
|
|
897
|
+
init_esm_shims();
|
|
898
|
+
var symbol = /* @__PURE__ */ Symbol.for("@achingbrain/uint8arraylist");
|
|
899
|
+
function findBufAndOffset(bufs, index) {
|
|
900
|
+
if (index == null || index < 0) {
|
|
901
|
+
throw new RangeError("index is out of bounds");
|
|
902
|
+
}
|
|
903
|
+
let offset = 0;
|
|
904
|
+
for (const buf of bufs) {
|
|
905
|
+
const bufEnd = offset + buf.byteLength;
|
|
906
|
+
if (index < bufEnd) {
|
|
907
|
+
return {
|
|
908
|
+
buf,
|
|
909
|
+
index: index - offset
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
offset = bufEnd;
|
|
913
|
+
}
|
|
914
|
+
throw new RangeError("index is out of bounds");
|
|
915
|
+
}
|
|
916
|
+
function isUint8ArrayList(value2) {
|
|
917
|
+
return Boolean(value2?.[symbol]);
|
|
918
|
+
}
|
|
919
|
+
var Uint8ArrayList = class _Uint8ArrayList {
|
|
920
|
+
bufs;
|
|
921
|
+
length;
|
|
922
|
+
[symbol] = true;
|
|
923
|
+
constructor(...data) {
|
|
924
|
+
this.bufs = [];
|
|
925
|
+
this.length = 0;
|
|
926
|
+
if (data.length > 0) {
|
|
927
|
+
this.appendAll(data);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
*[Symbol.iterator]() {
|
|
931
|
+
yield* this.bufs;
|
|
932
|
+
}
|
|
933
|
+
get byteLength() {
|
|
934
|
+
return this.length;
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Add one or more `bufs` to the end of this Uint8ArrayList
|
|
938
|
+
*/
|
|
939
|
+
append(...bufs) {
|
|
940
|
+
this.appendAll(bufs);
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Add all `bufs` to the end of this Uint8ArrayList
|
|
944
|
+
*/
|
|
945
|
+
appendAll(bufs) {
|
|
946
|
+
let length = 0;
|
|
947
|
+
for (const buf of bufs) {
|
|
948
|
+
if (buf instanceof Uint8Array) {
|
|
949
|
+
length += buf.byteLength;
|
|
950
|
+
this.bufs.push(buf);
|
|
951
|
+
} else if (isUint8ArrayList(buf)) {
|
|
952
|
+
length += buf.byteLength;
|
|
953
|
+
this.bufs.push(...buf.bufs);
|
|
954
|
+
} else {
|
|
955
|
+
throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
this.length += length;
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Add one or more `bufs` to the start of this Uint8ArrayList
|
|
962
|
+
*/
|
|
963
|
+
prepend(...bufs) {
|
|
964
|
+
this.prependAll(bufs);
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Add all `bufs` to the start of this Uint8ArrayList
|
|
968
|
+
*/
|
|
969
|
+
prependAll(bufs) {
|
|
970
|
+
let length = 0;
|
|
971
|
+
for (const buf of bufs.reverse()) {
|
|
972
|
+
if (buf instanceof Uint8Array) {
|
|
973
|
+
length += buf.byteLength;
|
|
974
|
+
this.bufs.unshift(buf);
|
|
975
|
+
} else if (isUint8ArrayList(buf)) {
|
|
976
|
+
length += buf.byteLength;
|
|
977
|
+
this.bufs.unshift(...buf.bufs);
|
|
978
|
+
} else {
|
|
979
|
+
throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
this.length += length;
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Read the value at `index`
|
|
986
|
+
*/
|
|
987
|
+
get(index) {
|
|
988
|
+
const res = findBufAndOffset(this.bufs, index);
|
|
989
|
+
return res.buf[res.index];
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Set the value at `index` to `value`
|
|
993
|
+
*/
|
|
994
|
+
set(index, value2) {
|
|
995
|
+
const res = findBufAndOffset(this.bufs, index);
|
|
996
|
+
res.buf[res.index] = value2;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Copy bytes from `buf` to the index specified by `offset`
|
|
1000
|
+
*/
|
|
1001
|
+
write(buf, offset = 0) {
|
|
1002
|
+
if (buf instanceof Uint8Array) {
|
|
1003
|
+
for (let i = 0; i < buf.length; i++) {
|
|
1004
|
+
this.set(offset + i, buf[i]);
|
|
1005
|
+
}
|
|
1006
|
+
} else if (isUint8ArrayList(buf)) {
|
|
1007
|
+
for (let i = 0; i < buf.length; i++) {
|
|
1008
|
+
this.set(offset + i, buf.get(i));
|
|
1009
|
+
}
|
|
1010
|
+
} else {
|
|
1011
|
+
throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Remove bytes from the front of the pool
|
|
1016
|
+
*/
|
|
1017
|
+
consume(bytes) {
|
|
1018
|
+
bytes = Math.trunc(bytes);
|
|
1019
|
+
if (Number.isNaN(bytes) || bytes <= 0) {
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
if (bytes === this.byteLength) {
|
|
1023
|
+
this.bufs = [];
|
|
1024
|
+
this.length = 0;
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
while (this.bufs.length > 0) {
|
|
1028
|
+
if (bytes >= this.bufs[0].byteLength) {
|
|
1029
|
+
bytes -= this.bufs[0].byteLength;
|
|
1030
|
+
this.length -= this.bufs[0].byteLength;
|
|
1031
|
+
this.bufs.shift();
|
|
1032
|
+
} else {
|
|
1033
|
+
this.bufs[0] = this.bufs[0].subarray(bytes);
|
|
1034
|
+
this.length -= bytes;
|
|
1035
|
+
break;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Extracts a section of an array and returns a new array.
|
|
1041
|
+
*
|
|
1042
|
+
* This is a copy operation as it is with Uint8Arrays and Arrays
|
|
1043
|
+
* - note this is different to the behaviour of Node Buffers.
|
|
1044
|
+
*/
|
|
1045
|
+
slice(beginInclusive, endExclusive) {
|
|
1046
|
+
const { bufs, length } = this._subList(beginInclusive, endExclusive);
|
|
1047
|
+
return concat(bufs, length);
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Returns a alloc from the given start and end element index.
|
|
1051
|
+
*
|
|
1052
|
+
* In the best case where the data extracted comes from a single Uint8Array
|
|
1053
|
+
* internally this is a no-copy operation otherwise it is a copy operation.
|
|
1054
|
+
*/
|
|
1055
|
+
subarray(beginInclusive, endExclusive) {
|
|
1056
|
+
const { bufs, length } = this._subList(beginInclusive, endExclusive);
|
|
1057
|
+
if (bufs.length === 1) {
|
|
1058
|
+
return bufs[0];
|
|
1059
|
+
}
|
|
1060
|
+
return concat(bufs, length);
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Returns a allocList from the given start and end element index.
|
|
1064
|
+
*
|
|
1065
|
+
* This is a no-copy operation.
|
|
1066
|
+
*/
|
|
1067
|
+
sublist(beginInclusive, endExclusive) {
|
|
1068
|
+
const { bufs, length } = this._subList(beginInclusive, endExclusive);
|
|
1069
|
+
const list = new _Uint8ArrayList();
|
|
1070
|
+
list.length = length;
|
|
1071
|
+
list.bufs = [...bufs];
|
|
1072
|
+
return list;
|
|
1073
|
+
}
|
|
1074
|
+
_subList(beginInclusive, endExclusive) {
|
|
1075
|
+
beginInclusive = beginInclusive ?? 0;
|
|
1076
|
+
endExclusive = endExclusive ?? this.length;
|
|
1077
|
+
if (beginInclusive < 0) {
|
|
1078
|
+
beginInclusive = this.length + beginInclusive;
|
|
1079
|
+
}
|
|
1080
|
+
if (endExclusive < 0) {
|
|
1081
|
+
endExclusive = this.length + endExclusive;
|
|
1082
|
+
}
|
|
1083
|
+
if (beginInclusive < 0 || endExclusive > this.length) {
|
|
1084
|
+
throw new RangeError("index is out of bounds");
|
|
1085
|
+
}
|
|
1086
|
+
if (beginInclusive === endExclusive) {
|
|
1087
|
+
return { bufs: [], length: 0 };
|
|
1088
|
+
}
|
|
1089
|
+
if (beginInclusive === 0 && endExclusive === this.length) {
|
|
1090
|
+
return { bufs: this.bufs, length: this.length };
|
|
1091
|
+
}
|
|
1092
|
+
const bufs = [];
|
|
1093
|
+
let offset = 0;
|
|
1094
|
+
for (let i = 0; i < this.bufs.length; i++) {
|
|
1095
|
+
const buf = this.bufs[i];
|
|
1096
|
+
const bufStart = offset;
|
|
1097
|
+
const bufEnd = bufStart + buf.byteLength;
|
|
1098
|
+
offset = bufEnd;
|
|
1099
|
+
if (beginInclusive >= bufEnd) {
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;
|
|
1103
|
+
const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;
|
|
1104
|
+
if (sliceStartInBuf && sliceEndsInBuf) {
|
|
1105
|
+
if (beginInclusive === bufStart && endExclusive === bufEnd) {
|
|
1106
|
+
bufs.push(buf);
|
|
1107
|
+
break;
|
|
1108
|
+
}
|
|
1109
|
+
const start = beginInclusive - bufStart;
|
|
1110
|
+
bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));
|
|
1111
|
+
break;
|
|
1112
|
+
}
|
|
1113
|
+
if (sliceStartInBuf) {
|
|
1114
|
+
if (beginInclusive === 0) {
|
|
1115
|
+
bufs.push(buf);
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
bufs.push(buf.subarray(beginInclusive - bufStart));
|
|
1119
|
+
continue;
|
|
1120
|
+
}
|
|
1121
|
+
if (sliceEndsInBuf) {
|
|
1122
|
+
if (endExclusive === bufEnd) {
|
|
1123
|
+
bufs.push(buf);
|
|
1124
|
+
break;
|
|
1125
|
+
}
|
|
1126
|
+
bufs.push(buf.subarray(0, endExclusive - bufStart));
|
|
1127
|
+
break;
|
|
1128
|
+
}
|
|
1129
|
+
bufs.push(buf);
|
|
1130
|
+
}
|
|
1131
|
+
return { bufs, length: endExclusive - beginInclusive };
|
|
1132
|
+
}
|
|
1133
|
+
indexOf(search, offset = 0) {
|
|
1134
|
+
if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {
|
|
1135
|
+
throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');
|
|
1136
|
+
}
|
|
1137
|
+
const needle = search instanceof Uint8Array ? search : search.subarray();
|
|
1138
|
+
offset = Number(offset ?? 0);
|
|
1139
|
+
if (isNaN(offset)) {
|
|
1140
|
+
offset = 0;
|
|
1141
|
+
}
|
|
1142
|
+
if (offset < 0) {
|
|
1143
|
+
offset = this.length + offset;
|
|
1144
|
+
}
|
|
1145
|
+
if (offset < 0) {
|
|
1146
|
+
offset = 0;
|
|
1147
|
+
}
|
|
1148
|
+
if (search.length === 0) {
|
|
1149
|
+
return offset > this.length ? this.length : offset;
|
|
1150
|
+
}
|
|
1151
|
+
const M = needle.byteLength;
|
|
1152
|
+
if (M === 0) {
|
|
1153
|
+
throw new TypeError("search must be at least 1 byte long");
|
|
1154
|
+
}
|
|
1155
|
+
const radix = 256;
|
|
1156
|
+
const rightmostPositions = new Int32Array(radix);
|
|
1157
|
+
for (let c = 0; c < radix; c++) {
|
|
1158
|
+
rightmostPositions[c] = -1;
|
|
1159
|
+
}
|
|
1160
|
+
for (let j = 0; j < M; j++) {
|
|
1161
|
+
rightmostPositions[needle[j]] = j;
|
|
1162
|
+
}
|
|
1163
|
+
const right = rightmostPositions;
|
|
1164
|
+
const lastIndex = this.byteLength - needle.byteLength;
|
|
1165
|
+
const lastPatIndex = needle.byteLength - 1;
|
|
1166
|
+
let skip;
|
|
1167
|
+
for (let i = offset; i <= lastIndex; i += skip) {
|
|
1168
|
+
skip = 0;
|
|
1169
|
+
for (let j = lastPatIndex; j >= 0; j--) {
|
|
1170
|
+
const char = this.get(i + j);
|
|
1171
|
+
if (needle[j] !== char) {
|
|
1172
|
+
skip = Math.max(1, j - right[char]);
|
|
1173
|
+
break;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
if (skip === 0) {
|
|
1177
|
+
return i;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
return -1;
|
|
1181
|
+
}
|
|
1182
|
+
getInt8(byteOffset) {
|
|
1183
|
+
const buf = this.subarray(byteOffset, byteOffset + 1);
|
|
1184
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1185
|
+
return view.getInt8(0);
|
|
1186
|
+
}
|
|
1187
|
+
setInt8(byteOffset, value2) {
|
|
1188
|
+
const buf = allocUnsafe(1);
|
|
1189
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1190
|
+
view.setInt8(0, value2);
|
|
1191
|
+
this.write(buf, byteOffset);
|
|
1192
|
+
}
|
|
1193
|
+
getInt16(byteOffset, littleEndian) {
|
|
1194
|
+
const buf = this.subarray(byteOffset, byteOffset + 2);
|
|
1195
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1196
|
+
return view.getInt16(0, littleEndian);
|
|
1197
|
+
}
|
|
1198
|
+
setInt16(byteOffset, value2, littleEndian) {
|
|
1199
|
+
const buf = alloc(2);
|
|
1200
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1201
|
+
view.setInt16(0, value2, littleEndian);
|
|
1202
|
+
this.write(buf, byteOffset);
|
|
1203
|
+
}
|
|
1204
|
+
getInt32(byteOffset, littleEndian) {
|
|
1205
|
+
const buf = this.subarray(byteOffset, byteOffset + 4);
|
|
1206
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1207
|
+
return view.getInt32(0, littleEndian);
|
|
1208
|
+
}
|
|
1209
|
+
setInt32(byteOffset, value2, littleEndian) {
|
|
1210
|
+
const buf = alloc(4);
|
|
1211
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1212
|
+
view.setInt32(0, value2, littleEndian);
|
|
1213
|
+
this.write(buf, byteOffset);
|
|
1214
|
+
}
|
|
1215
|
+
getBigInt64(byteOffset, littleEndian) {
|
|
1216
|
+
const buf = this.subarray(byteOffset, byteOffset + 8);
|
|
1217
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1218
|
+
return view.getBigInt64(0, littleEndian);
|
|
1219
|
+
}
|
|
1220
|
+
setBigInt64(byteOffset, value2, littleEndian) {
|
|
1221
|
+
const buf = alloc(8);
|
|
1222
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1223
|
+
view.setBigInt64(0, value2, littleEndian);
|
|
1224
|
+
this.write(buf, byteOffset);
|
|
1225
|
+
}
|
|
1226
|
+
getUint8(byteOffset) {
|
|
1227
|
+
const buf = this.subarray(byteOffset, byteOffset + 1);
|
|
1228
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1229
|
+
return view.getUint8(0);
|
|
1230
|
+
}
|
|
1231
|
+
setUint8(byteOffset, value2) {
|
|
1232
|
+
const buf = allocUnsafe(1);
|
|
1233
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1234
|
+
view.setUint8(0, value2);
|
|
1235
|
+
this.write(buf, byteOffset);
|
|
1236
|
+
}
|
|
1237
|
+
getUint16(byteOffset, littleEndian) {
|
|
1238
|
+
const buf = this.subarray(byteOffset, byteOffset + 2);
|
|
1239
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1240
|
+
return view.getUint16(0, littleEndian);
|
|
1241
|
+
}
|
|
1242
|
+
setUint16(byteOffset, value2, littleEndian) {
|
|
1243
|
+
const buf = alloc(2);
|
|
1244
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1245
|
+
view.setUint16(0, value2, littleEndian);
|
|
1246
|
+
this.write(buf, byteOffset);
|
|
1247
|
+
}
|
|
1248
|
+
getUint32(byteOffset, littleEndian) {
|
|
1249
|
+
const buf = this.subarray(byteOffset, byteOffset + 4);
|
|
1250
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1251
|
+
return view.getUint32(0, littleEndian);
|
|
1252
|
+
}
|
|
1253
|
+
setUint32(byteOffset, value2, littleEndian) {
|
|
1254
|
+
const buf = alloc(4);
|
|
1255
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1256
|
+
view.setUint32(0, value2, littleEndian);
|
|
1257
|
+
this.write(buf, byteOffset);
|
|
1258
|
+
}
|
|
1259
|
+
getBigUint64(byteOffset, littleEndian) {
|
|
1260
|
+
const buf = this.subarray(byteOffset, byteOffset + 8);
|
|
1261
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1262
|
+
return view.getBigUint64(0, littleEndian);
|
|
1263
|
+
}
|
|
1264
|
+
setBigUint64(byteOffset, value2, littleEndian) {
|
|
1265
|
+
const buf = alloc(8);
|
|
1266
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1267
|
+
view.setBigUint64(0, value2, littleEndian);
|
|
1268
|
+
this.write(buf, byteOffset);
|
|
1269
|
+
}
|
|
1270
|
+
getFloat32(byteOffset, littleEndian) {
|
|
1271
|
+
const buf = this.subarray(byteOffset, byteOffset + 4);
|
|
1272
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1273
|
+
return view.getFloat32(0, littleEndian);
|
|
1274
|
+
}
|
|
1275
|
+
setFloat32(byteOffset, value2, littleEndian) {
|
|
1276
|
+
const buf = alloc(4);
|
|
1277
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1278
|
+
view.setFloat32(0, value2, littleEndian);
|
|
1279
|
+
this.write(buf, byteOffset);
|
|
1280
|
+
}
|
|
1281
|
+
getFloat64(byteOffset, littleEndian) {
|
|
1282
|
+
const buf = this.subarray(byteOffset, byteOffset + 8);
|
|
1283
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1284
|
+
return view.getFloat64(0, littleEndian);
|
|
1285
|
+
}
|
|
1286
|
+
setFloat64(byteOffset, value2, littleEndian) {
|
|
1287
|
+
const buf = alloc(8);
|
|
1288
|
+
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1289
|
+
view.setFloat64(0, value2, littleEndian);
|
|
1290
|
+
this.write(buf, byteOffset);
|
|
1291
|
+
}
|
|
1292
|
+
equals(other) {
|
|
1293
|
+
if (other == null) {
|
|
1294
|
+
return false;
|
|
1295
|
+
}
|
|
1296
|
+
if (!(other instanceof _Uint8ArrayList)) {
|
|
1297
|
+
return false;
|
|
1298
|
+
}
|
|
1299
|
+
if (other.bufs.length !== this.bufs.length) {
|
|
1300
|
+
return false;
|
|
1301
|
+
}
|
|
1302
|
+
for (let i = 0; i < this.bufs.length; i++) {
|
|
1303
|
+
if (!equals(this.bufs[i], other.bufs[i])) {
|
|
1304
|
+
return false;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return true;
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this
|
|
1311
|
+
* method if you know the total size of all the Uint8Arrays ahead of time.
|
|
1312
|
+
*/
|
|
1313
|
+
static fromUint8Arrays(bufs, length) {
|
|
1314
|
+
const list = new _Uint8ArrayList();
|
|
1315
|
+
list.bufs = bufs;
|
|
1316
|
+
if (length == null) {
|
|
1317
|
+
length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);
|
|
1318
|
+
}
|
|
1319
|
+
list.length = length;
|
|
1320
|
+
return list;
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
|
|
1324
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/multiaddr/get-net-config.js
|
|
1325
|
+
init_esm_shims();
|
|
1326
|
+
function getNetConfig(ma) {
|
|
1327
|
+
const components = ma.getComponents();
|
|
1328
|
+
const config = {};
|
|
1329
|
+
let index = 0;
|
|
1330
|
+
if (components[index]?.name === "ip6zone") {
|
|
1331
|
+
config.zone = `${components[index].value}`;
|
|
1332
|
+
index++;
|
|
1333
|
+
}
|
|
1334
|
+
if (components[index].name === "ip4" || components[index].name === "ip6") {
|
|
1335
|
+
config.type = components[index].name;
|
|
1336
|
+
config.host = components[index].value;
|
|
1337
|
+
index++;
|
|
1338
|
+
} else if (components[index].name === "dns" || components[index].name === "dns4" || components[index].name === "dns6") {
|
|
1339
|
+
config.type = components[index].name;
|
|
1340
|
+
config.host = components[index].value;
|
|
1341
|
+
index++;
|
|
1342
|
+
} else if (components[index].name === "dnsaddr") {
|
|
1343
|
+
config.type = components[index].name;
|
|
1344
|
+
config.host = `_dnsaddr.${components[index].value}`;
|
|
1345
|
+
index++;
|
|
1346
|
+
}
|
|
1347
|
+
if (components[index]?.name === "tcp" || components[index]?.name === "udp") {
|
|
1348
|
+
config.protocol = components[index].name === "tcp" ? "tcp" : "udp";
|
|
1349
|
+
config.port = parseInt(`${components[index].value}`);
|
|
1350
|
+
index++;
|
|
1351
|
+
}
|
|
1352
|
+
if (components[index]?.name === "ipcidr") {
|
|
1353
|
+
if (config.type === "ip4") {
|
|
1354
|
+
config.cidr = parseInt(`${components[index].value}`);
|
|
1355
|
+
} else if (config.type === "ip6") {
|
|
1356
|
+
config.cidr = `${components[index].value}`;
|
|
1357
|
+
}
|
|
1358
|
+
index++;
|
|
1359
|
+
}
|
|
1360
|
+
if (config.type == null || config.host == null) {
|
|
1361
|
+
throw new InvalidParametersError(`Multiaddr ${ma} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);
|
|
1362
|
+
}
|
|
1363
|
+
if (components[index]?.name === "tls" && components[index + 1]?.name === "sni") {
|
|
1364
|
+
config.sni = components[index + 1].value;
|
|
1365
|
+
index += 2;
|
|
1366
|
+
}
|
|
1367
|
+
return config;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// ../../node_modules/.pnpm/@chainsafe+is-ip@2.1.0/node_modules/@chainsafe/is-ip/lib/is-ip.node.js
|
|
1371
|
+
init_esm_shims();
|
|
1372
|
+
|
|
1373
|
+
// ../../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/dist/src/index.js
|
|
1374
|
+
init_esm_shims();
|
|
1375
|
+
|
|
1376
|
+
// ../../node_modules/.pnpm/p-defer@4.0.1/node_modules/p-defer/index.js
|
|
1377
|
+
init_esm_shims();
|
|
1378
|
+
function pDefer() {
|
|
1379
|
+
const deferred = {};
|
|
1380
|
+
deferred.promise = new Promise((resolve, reject) => {
|
|
1381
|
+
deferred.resolve = resolve;
|
|
1382
|
+
deferred.reject = reject;
|
|
1383
|
+
});
|
|
1384
|
+
return deferred;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// ../../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/dist/src/fifo.js
|
|
1388
|
+
init_esm_shims();
|
|
1389
|
+
var FixedFIFO = class {
|
|
1390
|
+
buffer;
|
|
1391
|
+
mask;
|
|
1392
|
+
top;
|
|
1393
|
+
btm;
|
|
1394
|
+
next;
|
|
1395
|
+
constructor(hwm) {
|
|
1396
|
+
if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) {
|
|
1397
|
+
throw new Error("Max size for a FixedFIFO should be a power of two");
|
|
1398
|
+
}
|
|
1399
|
+
this.buffer = new Array(hwm);
|
|
1400
|
+
this.mask = hwm - 1;
|
|
1401
|
+
this.top = 0;
|
|
1402
|
+
this.btm = 0;
|
|
1403
|
+
this.next = null;
|
|
1404
|
+
}
|
|
1405
|
+
push(data) {
|
|
1406
|
+
if (this.buffer[this.top] !== void 0) {
|
|
1407
|
+
return false;
|
|
1408
|
+
}
|
|
1409
|
+
this.buffer[this.top] = data;
|
|
1410
|
+
this.top = this.top + 1 & this.mask;
|
|
1411
|
+
return true;
|
|
1412
|
+
}
|
|
1413
|
+
shift() {
|
|
1414
|
+
const last = this.buffer[this.btm];
|
|
1415
|
+
if (last === void 0) {
|
|
1416
|
+
return void 0;
|
|
1417
|
+
}
|
|
1418
|
+
this.buffer[this.btm] = void 0;
|
|
1419
|
+
this.btm = this.btm + 1 & this.mask;
|
|
1420
|
+
return last;
|
|
1421
|
+
}
|
|
1422
|
+
isEmpty() {
|
|
1423
|
+
return this.buffer[this.btm] === void 0;
|
|
1424
|
+
}
|
|
1425
|
+
};
|
|
1426
|
+
var FIFO = class {
|
|
1427
|
+
size;
|
|
1428
|
+
hwm;
|
|
1429
|
+
head;
|
|
1430
|
+
tail;
|
|
1431
|
+
constructor(options = {}) {
|
|
1432
|
+
this.hwm = options.splitLimit ?? 16;
|
|
1433
|
+
this.head = new FixedFIFO(this.hwm);
|
|
1434
|
+
this.tail = this.head;
|
|
1435
|
+
this.size = 0;
|
|
1436
|
+
}
|
|
1437
|
+
calculateSize(obj) {
|
|
1438
|
+
if (obj?.byteLength != null) {
|
|
1439
|
+
return obj.byteLength;
|
|
1440
|
+
}
|
|
1441
|
+
return 1;
|
|
1442
|
+
}
|
|
1443
|
+
push(val) {
|
|
1444
|
+
if (val?.value != null) {
|
|
1445
|
+
this.size += this.calculateSize(val.value);
|
|
1446
|
+
}
|
|
1447
|
+
if (!this.head.push(val)) {
|
|
1448
|
+
const prev = this.head;
|
|
1449
|
+
this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
|
|
1450
|
+
this.head.push(val);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
shift() {
|
|
1454
|
+
let val = this.tail.shift();
|
|
1455
|
+
if (val === void 0 && this.tail.next != null) {
|
|
1456
|
+
const next = this.tail.next;
|
|
1457
|
+
this.tail.next = null;
|
|
1458
|
+
this.tail = next;
|
|
1459
|
+
val = this.tail.shift();
|
|
1460
|
+
}
|
|
1461
|
+
if (val?.value != null) {
|
|
1462
|
+
this.size -= this.calculateSize(val.value);
|
|
1463
|
+
}
|
|
1464
|
+
return val;
|
|
1465
|
+
}
|
|
1466
|
+
isEmpty() {
|
|
1467
|
+
return this.head.isEmpty();
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1470
|
+
|
|
1471
|
+
// ../../node_modules/.pnpm/it-pushable@3.2.3/node_modules/it-pushable/dist/src/index.js
|
|
1472
|
+
var AbortError = class extends Error {
|
|
1473
|
+
type;
|
|
1474
|
+
code;
|
|
1475
|
+
constructor(message, code2) {
|
|
1476
|
+
super(message ?? "The operation was aborted");
|
|
1477
|
+
this.type = "aborted";
|
|
1478
|
+
this.code = code2 ?? "ABORT_ERR";
|
|
1479
|
+
}
|
|
1480
|
+
};
|
|
1481
|
+
function pushable(options = {}) {
|
|
1482
|
+
const getNext = (buffer) => {
|
|
1483
|
+
const next = buffer.shift();
|
|
1484
|
+
if (next == null) {
|
|
1485
|
+
return { done: true };
|
|
1486
|
+
}
|
|
1487
|
+
if (next.error != null) {
|
|
1488
|
+
throw next.error;
|
|
1489
|
+
}
|
|
1490
|
+
return {
|
|
1491
|
+
done: next.done === true,
|
|
1492
|
+
// @ts-expect-error if done is false, value will be present
|
|
1493
|
+
value: next.value
|
|
1494
|
+
};
|
|
1495
|
+
};
|
|
1496
|
+
return _pushable(getNext, options);
|
|
1497
|
+
}
|
|
1498
|
+
function _pushable(getNext, options) {
|
|
1499
|
+
options = options ?? {};
|
|
1500
|
+
let onEnd = options.onEnd;
|
|
1501
|
+
let buffer = new FIFO();
|
|
1502
|
+
let pushable2;
|
|
1503
|
+
let onNext;
|
|
1504
|
+
let ended;
|
|
1505
|
+
let drain = pDefer();
|
|
1506
|
+
const waitNext = async () => {
|
|
1507
|
+
try {
|
|
1508
|
+
if (!buffer.isEmpty()) {
|
|
1509
|
+
return getNext(buffer);
|
|
1510
|
+
}
|
|
1511
|
+
if (ended) {
|
|
1512
|
+
return { done: true };
|
|
1513
|
+
}
|
|
1514
|
+
return await new Promise((resolve, reject) => {
|
|
1515
|
+
onNext = (next) => {
|
|
1516
|
+
onNext = null;
|
|
1517
|
+
buffer.push(next);
|
|
1518
|
+
try {
|
|
1519
|
+
resolve(getNext(buffer));
|
|
1520
|
+
} catch (err) {
|
|
1521
|
+
reject(err);
|
|
1522
|
+
}
|
|
1523
|
+
return pushable2;
|
|
1524
|
+
};
|
|
1525
|
+
});
|
|
1526
|
+
} finally {
|
|
1527
|
+
if (buffer.isEmpty()) {
|
|
1528
|
+
queueMicrotask(() => {
|
|
1529
|
+
drain.resolve();
|
|
1530
|
+
drain = pDefer();
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
};
|
|
1535
|
+
const bufferNext = (next) => {
|
|
1536
|
+
if (onNext != null) {
|
|
1537
|
+
return onNext(next);
|
|
1538
|
+
}
|
|
1539
|
+
buffer.push(next);
|
|
1540
|
+
return pushable2;
|
|
1541
|
+
};
|
|
1542
|
+
const bufferError = (err) => {
|
|
1543
|
+
buffer = new FIFO();
|
|
1544
|
+
if (onNext != null) {
|
|
1545
|
+
return onNext({ error: err });
|
|
1546
|
+
}
|
|
1547
|
+
buffer.push({ error: err });
|
|
1548
|
+
return pushable2;
|
|
1549
|
+
};
|
|
1550
|
+
const push = (value2) => {
|
|
1551
|
+
if (ended) {
|
|
1552
|
+
return pushable2;
|
|
1553
|
+
}
|
|
1554
|
+
if (options?.objectMode !== true && value2?.byteLength == null) {
|
|
1555
|
+
throw new Error("objectMode was not true but tried to push non-Uint8Array value");
|
|
1556
|
+
}
|
|
1557
|
+
return bufferNext({ done: false, value: value2 });
|
|
1558
|
+
};
|
|
1559
|
+
const end = (err) => {
|
|
1560
|
+
if (ended)
|
|
1561
|
+
return pushable2;
|
|
1562
|
+
ended = true;
|
|
1563
|
+
return err != null ? bufferError(err) : bufferNext({ done: true });
|
|
1564
|
+
};
|
|
1565
|
+
const _return = () => {
|
|
1566
|
+
buffer = new FIFO();
|
|
1567
|
+
end();
|
|
1568
|
+
return { done: true };
|
|
1569
|
+
};
|
|
1570
|
+
const _throw = (err) => {
|
|
1571
|
+
end(err);
|
|
1572
|
+
return { done: true };
|
|
1573
|
+
};
|
|
1574
|
+
pushable2 = {
|
|
1575
|
+
[Symbol.asyncIterator]() {
|
|
1576
|
+
return this;
|
|
1577
|
+
},
|
|
1578
|
+
next: waitNext,
|
|
1579
|
+
return: _return,
|
|
1580
|
+
throw: _throw,
|
|
1581
|
+
push,
|
|
1582
|
+
end,
|
|
1583
|
+
get readableLength() {
|
|
1584
|
+
return buffer.size;
|
|
1585
|
+
},
|
|
1586
|
+
onEmpty: async (options2) => {
|
|
1587
|
+
const signal = options2?.signal;
|
|
1588
|
+
signal?.throwIfAborted();
|
|
1589
|
+
if (buffer.isEmpty()) {
|
|
1590
|
+
return;
|
|
1591
|
+
}
|
|
1592
|
+
let cancel;
|
|
1593
|
+
let listener;
|
|
1594
|
+
if (signal != null) {
|
|
1595
|
+
cancel = new Promise((resolve, reject) => {
|
|
1596
|
+
listener = () => {
|
|
1597
|
+
reject(new AbortError());
|
|
1598
|
+
};
|
|
1599
|
+
signal.addEventListener("abort", listener);
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
try {
|
|
1603
|
+
await Promise.race([
|
|
1604
|
+
drain.promise,
|
|
1605
|
+
cancel
|
|
1606
|
+
]);
|
|
1607
|
+
} finally {
|
|
1608
|
+
if (listener != null && signal != null) {
|
|
1609
|
+
signal?.removeEventListener("abort", listener);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
};
|
|
1614
|
+
if (onEnd == null) {
|
|
1615
|
+
return pushable2;
|
|
1616
|
+
}
|
|
1617
|
+
const _pushable2 = pushable2;
|
|
1618
|
+
pushable2 = {
|
|
1619
|
+
[Symbol.asyncIterator]() {
|
|
1620
|
+
return this;
|
|
1621
|
+
},
|
|
1622
|
+
next() {
|
|
1623
|
+
return _pushable2.next();
|
|
1624
|
+
},
|
|
1625
|
+
throw(err) {
|
|
1626
|
+
_pushable2.throw(err);
|
|
1627
|
+
if (onEnd != null) {
|
|
1628
|
+
onEnd(err);
|
|
1629
|
+
onEnd = void 0;
|
|
1630
|
+
}
|
|
1631
|
+
return { done: true };
|
|
1632
|
+
},
|
|
1633
|
+
return() {
|
|
1634
|
+
_pushable2.return();
|
|
1635
|
+
if (onEnd != null) {
|
|
1636
|
+
onEnd();
|
|
1637
|
+
onEnd = void 0;
|
|
1638
|
+
}
|
|
1639
|
+
return { done: true };
|
|
1640
|
+
},
|
|
1641
|
+
push,
|
|
1642
|
+
end(err) {
|
|
1643
|
+
_pushable2.end(err);
|
|
1644
|
+
if (onEnd != null) {
|
|
1645
|
+
onEnd(err);
|
|
1646
|
+
onEnd = void 0;
|
|
1647
|
+
}
|
|
1648
|
+
return pushable2;
|
|
1649
|
+
},
|
|
1650
|
+
get readableLength() {
|
|
1651
|
+
return _pushable2.readableLength;
|
|
1652
|
+
},
|
|
1653
|
+
onEmpty: (opts) => {
|
|
1654
|
+
return _pushable2.onEmpty(opts);
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
return pushable2;
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/debounce.js
|
|
1661
|
+
init_esm_shims();
|
|
1662
|
+
function debounce(func, wait) {
|
|
1663
|
+
let timeout;
|
|
1664
|
+
const output = function() {
|
|
1665
|
+
const later = function() {
|
|
1666
|
+
timeout = void 0;
|
|
1667
|
+
void func();
|
|
1668
|
+
};
|
|
1669
|
+
clearTimeout(timeout);
|
|
1670
|
+
timeout = setTimeout(later, wait);
|
|
1671
|
+
};
|
|
1672
|
+
output.start = () => {
|
|
1673
|
+
};
|
|
1674
|
+
output.stop = () => {
|
|
1675
|
+
clearTimeout(timeout);
|
|
1676
|
+
};
|
|
1677
|
+
return output;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/errors.js
|
|
1681
|
+
init_esm_shims();
|
|
1682
|
+
var StreamClosedError = class extends Error {
|
|
1683
|
+
static name = "StreamClosedError";
|
|
1684
|
+
name = "StreamClosedError";
|
|
1685
|
+
};
|
|
1686
|
+
|
|
1687
|
+
// ../../node_modules/.pnpm/race-signal@2.0.0/node_modules/race-signal/dist/src/index.js
|
|
1688
|
+
init_esm_shims();
|
|
1689
|
+
function defaultTranslate(signal) {
|
|
1690
|
+
return signal.reason;
|
|
1691
|
+
}
|
|
1692
|
+
async function raceSignal(promise, signal, opts) {
|
|
1693
|
+
if (signal == null) {
|
|
1694
|
+
return promise;
|
|
1695
|
+
}
|
|
1696
|
+
const translateError = defaultTranslate;
|
|
1697
|
+
if (signal.aborted) {
|
|
1698
|
+
promise.catch(() => {
|
|
1699
|
+
});
|
|
1700
|
+
return Promise.reject(translateError(signal));
|
|
1701
|
+
}
|
|
1702
|
+
let listener;
|
|
1703
|
+
try {
|
|
1704
|
+
return await Promise.race([
|
|
1705
|
+
promise,
|
|
1706
|
+
new Promise((resolve, reject) => {
|
|
1707
|
+
listener = () => {
|
|
1708
|
+
reject(translateError(signal));
|
|
1709
|
+
};
|
|
1710
|
+
signal.addEventListener("abort", listener);
|
|
1711
|
+
})
|
|
1712
|
+
]);
|
|
1713
|
+
} finally {
|
|
1714
|
+
if (listener != null) {
|
|
1715
|
+
signal.removeEventListener("abort", listener);
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/abstract-message-stream.js
|
|
1721
|
+
init_esm_shims();
|
|
1722
|
+
var DEFAULT_MAX_READ_BUFFER_LENGTH = Math.pow(2, 20) * 4;
|
|
1723
|
+
var AbstractMessageStream = class extends TypedEventEmitter {
|
|
1724
|
+
status;
|
|
1725
|
+
timeline;
|
|
1726
|
+
inactivityTimeout;
|
|
1727
|
+
maxReadBufferLength;
|
|
1728
|
+
maxWriteBufferLength;
|
|
1729
|
+
log;
|
|
1730
|
+
direction;
|
|
1731
|
+
maxMessageSize;
|
|
1732
|
+
readStatus;
|
|
1733
|
+
writeStatus;
|
|
1734
|
+
remoteReadStatus;
|
|
1735
|
+
remoteWriteStatus;
|
|
1736
|
+
writableNeedsDrain;
|
|
1737
|
+
/**
|
|
1738
|
+
* Any data stored here is emitted before any new incoming data.
|
|
1739
|
+
*
|
|
1740
|
+
* This is used when the stream is paused or if data is pushed onto the stream
|
|
1741
|
+
*/
|
|
1742
|
+
readBuffer;
|
|
1743
|
+
writeBuffer;
|
|
1744
|
+
sendingData;
|
|
1745
|
+
onDrainPromise;
|
|
1746
|
+
constructor(init) {
|
|
1747
|
+
super();
|
|
1748
|
+
this.status = "open";
|
|
1749
|
+
this.log = init.log;
|
|
1750
|
+
this.direction = init.direction ?? "outbound";
|
|
1751
|
+
this.inactivityTimeout = init.inactivityTimeout ?? 12e4;
|
|
1752
|
+
this.maxReadBufferLength = init.maxReadBufferLength ?? DEFAULT_MAX_READ_BUFFER_LENGTH;
|
|
1753
|
+
this.maxWriteBufferLength = init.maxWriteBufferLength;
|
|
1754
|
+
this.maxMessageSize = init.maxMessageSize;
|
|
1755
|
+
this.readBuffer = new Uint8ArrayList();
|
|
1756
|
+
this.writeBuffer = new Uint8ArrayList();
|
|
1757
|
+
this.readStatus = "readable";
|
|
1758
|
+
this.remoteReadStatus = "readable";
|
|
1759
|
+
this.writeStatus = "writable";
|
|
1760
|
+
this.remoteWriteStatus = "writable";
|
|
1761
|
+
this.sendingData = false;
|
|
1762
|
+
this.writableNeedsDrain = false;
|
|
1763
|
+
this.timeline = {
|
|
1764
|
+
open: Date.now()
|
|
1765
|
+
};
|
|
1766
|
+
this.processSendQueue = this.processSendQueue.bind(this);
|
|
1767
|
+
const continueSendingOnDrain = () => {
|
|
1768
|
+
if (this.writableNeedsDrain) {
|
|
1769
|
+
this.log.trace("drain event received, continue sending data");
|
|
1770
|
+
this.writableNeedsDrain = false;
|
|
1771
|
+
this.processSendQueue();
|
|
1772
|
+
}
|
|
1773
|
+
this.onDrainPromise?.resolve();
|
|
1774
|
+
};
|
|
1775
|
+
this.addEventListener("drain", continueSendingOnDrain);
|
|
1776
|
+
const rejectOnDrainOnClose = (evt) => {
|
|
1777
|
+
this.onDrainPromise?.reject(evt.error ?? new StreamClosedError());
|
|
1778
|
+
};
|
|
1779
|
+
this.addEventListener("close", rejectOnDrainOnClose);
|
|
1780
|
+
}
|
|
1781
|
+
get readBufferLength() {
|
|
1782
|
+
return this.readBuffer.byteLength;
|
|
1783
|
+
}
|
|
1784
|
+
get writeBufferLength() {
|
|
1785
|
+
return this.writeBuffer.byteLength;
|
|
1786
|
+
}
|
|
1787
|
+
async onDrain(options) {
|
|
1788
|
+
if (this.writableNeedsDrain !== true) {
|
|
1789
|
+
return Promise.resolve();
|
|
1790
|
+
}
|
|
1791
|
+
if (this.onDrainPromise == null) {
|
|
1792
|
+
this.onDrainPromise = Promise.withResolvers();
|
|
1793
|
+
}
|
|
1794
|
+
return raceSignal(this.onDrainPromise.promise, options?.signal);
|
|
1795
|
+
}
|
|
1796
|
+
async *[Symbol.asyncIterator]() {
|
|
1797
|
+
if (this.readStatus !== "readable" && this.readStatus !== "paused") {
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
const output = pushable();
|
|
1801
|
+
const streamAsyncIterableOnMessageListener = (evt) => {
|
|
1802
|
+
output.push(evt.data);
|
|
1803
|
+
};
|
|
1804
|
+
this.addEventListener("message", streamAsyncIterableOnMessageListener);
|
|
1805
|
+
const streamAsyncIterableOnCloseListener = (evt) => {
|
|
1806
|
+
output.end(evt.error);
|
|
1807
|
+
};
|
|
1808
|
+
this.addEventListener("close", streamAsyncIterableOnCloseListener);
|
|
1809
|
+
const streamAsyncIterableOnRemoteCloseWriteListener = () => {
|
|
1810
|
+
output.end();
|
|
1811
|
+
};
|
|
1812
|
+
this.addEventListener("remoteCloseWrite", streamAsyncIterableOnRemoteCloseWriteListener);
|
|
1813
|
+
try {
|
|
1814
|
+
yield* output;
|
|
1815
|
+
} finally {
|
|
1816
|
+
this.removeEventListener("message", streamAsyncIterableOnMessageListener);
|
|
1817
|
+
this.removeEventListener("close", streamAsyncIterableOnCloseListener);
|
|
1818
|
+
this.removeEventListener("remoteCloseWrite", streamAsyncIterableOnRemoteCloseWriteListener);
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
isReadable() {
|
|
1822
|
+
return this.status === "open";
|
|
1823
|
+
}
|
|
1824
|
+
send(data) {
|
|
1825
|
+
if (this.writeStatus === "closed" || this.writeStatus === "closing") {
|
|
1826
|
+
throw new StreamStateError(`Cannot write to a stream that is ${this.writeStatus}`);
|
|
1827
|
+
}
|
|
1828
|
+
this.log.trace("append %d bytes to write buffer", data.byteLength);
|
|
1829
|
+
this.writeBuffer.append(data);
|
|
1830
|
+
return this.processSendQueue();
|
|
1831
|
+
}
|
|
1832
|
+
/**
|
|
1833
|
+
* Close immediately for reading and writing and send a reset message (local
|
|
1834
|
+
* error)
|
|
1835
|
+
*/
|
|
1836
|
+
abort(err) {
|
|
1837
|
+
if (this.status === "aborted" || this.status === "reset" || this.status === "closed") {
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
this.log.error("abort with error - %e", err);
|
|
1841
|
+
this.status = "aborted";
|
|
1842
|
+
if (this.readBuffer.byteLength > 0) {
|
|
1843
|
+
this.readBuffer.consume(this.readBuffer.byteLength);
|
|
1844
|
+
}
|
|
1845
|
+
if (this.writeBuffer.byteLength > 0) {
|
|
1846
|
+
this.writeBuffer.consume(this.writeBuffer.byteLength);
|
|
1847
|
+
this.safeDispatchEvent("idle");
|
|
1848
|
+
}
|
|
1849
|
+
this.writeStatus = "closed";
|
|
1850
|
+
this.remoteWriteStatus = "closed";
|
|
1851
|
+
this.readStatus = "closed";
|
|
1852
|
+
this.remoteReadStatus = "closed";
|
|
1853
|
+
this.timeline.close = Date.now();
|
|
1854
|
+
try {
|
|
1855
|
+
this.sendReset(err);
|
|
1856
|
+
} catch (err2) {
|
|
1857
|
+
this.log("failed to send reset to remote - %e", err2);
|
|
1858
|
+
}
|
|
1859
|
+
this.dispatchEvent(new StreamAbortEvent(err));
|
|
1860
|
+
}
|
|
1861
|
+
pause() {
|
|
1862
|
+
if (this.readStatus === "closed" || this.readStatus === "closing") {
|
|
1863
|
+
throw new StreamStateError("Cannot pause a stream that is closing/closed");
|
|
1864
|
+
}
|
|
1865
|
+
if (this.readStatus === "paused") {
|
|
1866
|
+
return;
|
|
1867
|
+
}
|
|
1868
|
+
this.readStatus = "paused";
|
|
1869
|
+
this.sendPause();
|
|
1870
|
+
}
|
|
1871
|
+
resume() {
|
|
1872
|
+
if (this.readStatus === "closed" || this.readStatus === "closing") {
|
|
1873
|
+
throw new StreamStateError("Cannot resume a stream that is closing/closed");
|
|
1874
|
+
}
|
|
1875
|
+
if (this.readStatus === "readable") {
|
|
1876
|
+
return;
|
|
1877
|
+
}
|
|
1878
|
+
this.readStatus = "readable";
|
|
1879
|
+
this.dispatchReadBuffer();
|
|
1880
|
+
this.sendResume();
|
|
1881
|
+
}
|
|
1882
|
+
push(data) {
|
|
1883
|
+
if (this.readStatus === "closed" || this.readStatus === "closing") {
|
|
1884
|
+
throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`);
|
|
1885
|
+
}
|
|
1886
|
+
if (data.byteLength === 0) {
|
|
1887
|
+
return;
|
|
1888
|
+
}
|
|
1889
|
+
this.readBuffer.append(data);
|
|
1890
|
+
if (this.readStatus === "paused" || this.listenerCount("message") === 0) {
|
|
1891
|
+
this.checkReadBufferLength();
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
setTimeout(() => {
|
|
1895
|
+
this.dispatchReadBuffer();
|
|
1896
|
+
}, 0);
|
|
1897
|
+
}
|
|
1898
|
+
unshift(data) {
|
|
1899
|
+
if (this.readStatus === "closed" || this.readStatus === "closing") {
|
|
1900
|
+
throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`);
|
|
1901
|
+
}
|
|
1902
|
+
if (data.byteLength === 0) {
|
|
1903
|
+
return;
|
|
1904
|
+
}
|
|
1905
|
+
this.readBuffer.prepend(data);
|
|
1906
|
+
if (this.readStatus === "paused" || this.listenerCount("message") === 0) {
|
|
1907
|
+
this.checkReadBufferLength();
|
|
1908
|
+
return;
|
|
1909
|
+
}
|
|
1910
|
+
setTimeout(() => {
|
|
1911
|
+
this.dispatchReadBuffer();
|
|
1912
|
+
}, 0);
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* When an extending class reads data from it's implementation-specific source,
|
|
1916
|
+
* call this method to allow the stream consumer to read the data.
|
|
1917
|
+
*/
|
|
1918
|
+
onData(data) {
|
|
1919
|
+
if (data.byteLength === 0) {
|
|
1920
|
+
return;
|
|
1921
|
+
}
|
|
1922
|
+
if (this.readStatus === "closing" || this.readStatus === "closed") {
|
|
1923
|
+
this.log("ignoring data - read status %s", this.readStatus);
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
this.readBuffer.append(data);
|
|
1927
|
+
this.dispatchReadBuffer();
|
|
1928
|
+
}
|
|
1929
|
+
addEventListener(...args) {
|
|
1930
|
+
super.addEventListener.apply(this, args);
|
|
1931
|
+
if (args[0] === "message" && this.readBuffer.byteLength > 0) {
|
|
1932
|
+
queueMicrotask(() => {
|
|
1933
|
+
this.dispatchReadBuffer();
|
|
1934
|
+
});
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Receive a reset message - close immediately for reading and writing (remote
|
|
1939
|
+
* error)
|
|
1940
|
+
*/
|
|
1941
|
+
onRemoteReset() {
|
|
1942
|
+
this.log("remote reset");
|
|
1943
|
+
this.status = "reset";
|
|
1944
|
+
this.writeStatus = "closed";
|
|
1945
|
+
this.remoteWriteStatus = "closed";
|
|
1946
|
+
this.remoteReadStatus = "closed";
|
|
1947
|
+
this.timeline.close = Date.now();
|
|
1948
|
+
if (this.readBuffer.byteLength === 0) {
|
|
1949
|
+
this.readStatus = "closed";
|
|
1950
|
+
}
|
|
1951
|
+
const err = new StreamResetError();
|
|
1952
|
+
this.dispatchEvent(new StreamResetEvent(err));
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* The underlying resource or transport this stream uses has closed - it is
|
|
1956
|
+
* not possible to send any more messages though any data still in the read
|
|
1957
|
+
* buffer may still be read
|
|
1958
|
+
*/
|
|
1959
|
+
onTransportClosed(err) {
|
|
1960
|
+
this.log("transport closed");
|
|
1961
|
+
if (this.readStatus === "readable" && this.readBuffer.byteLength === 0) {
|
|
1962
|
+
this.log("close readable end after transport closed and read buffer is empty");
|
|
1963
|
+
this.readStatus = "closed";
|
|
1964
|
+
}
|
|
1965
|
+
if (this.remoteReadStatus !== "closed") {
|
|
1966
|
+
this.remoteReadStatus = "closed";
|
|
1967
|
+
}
|
|
1968
|
+
if (this.remoteWriteStatus !== "closed") {
|
|
1969
|
+
this.remoteWriteStatus = "closed";
|
|
1970
|
+
}
|
|
1971
|
+
if (this.writeStatus !== "closed") {
|
|
1972
|
+
this.writeStatus = "closed";
|
|
1973
|
+
}
|
|
1974
|
+
if (err != null) {
|
|
1975
|
+
this.abort(err);
|
|
1976
|
+
} else {
|
|
1977
|
+
if (this.status === "open" || this.status === "closing") {
|
|
1978
|
+
this.timeline.close = Date.now();
|
|
1979
|
+
this.status = "closed";
|
|
1980
|
+
this.writeStatus = "closed";
|
|
1981
|
+
this.remoteWriteStatus = "closed";
|
|
1982
|
+
this.remoteReadStatus = "closed";
|
|
1983
|
+
this.dispatchEvent(new StreamCloseEvent());
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
/**
|
|
1988
|
+
* Called by extending classes when the remote closes its writable end
|
|
1989
|
+
*/
|
|
1990
|
+
onRemoteCloseWrite() {
|
|
1991
|
+
if (this.remoteWriteStatus === "closed") {
|
|
1992
|
+
return;
|
|
1993
|
+
}
|
|
1994
|
+
this.log.trace("on remote close write");
|
|
1995
|
+
this.remoteWriteStatus = "closed";
|
|
1996
|
+
this.safeDispatchEvent("remoteCloseWrite");
|
|
1997
|
+
if (this.writeStatus === "closed") {
|
|
1998
|
+
this.onTransportClosed();
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Called by extending classes when the remote closes its readable end
|
|
2003
|
+
*/
|
|
2004
|
+
onRemoteCloseRead() {
|
|
2005
|
+
this.log.trace("on remote close read");
|
|
2006
|
+
this.remoteReadStatus = "closed";
|
|
2007
|
+
if (this.writeBuffer.byteLength > 0) {
|
|
2008
|
+
this.writeBuffer.consume(this.writeBuffer.byteLength);
|
|
2009
|
+
this.safeDispatchEvent("idle");
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
processSendQueue() {
|
|
2013
|
+
if (this.writableNeedsDrain) {
|
|
2014
|
+
this.log.trace("not processing send queue as drain is required");
|
|
2015
|
+
this.checkWriteBufferLength();
|
|
2016
|
+
return false;
|
|
2017
|
+
}
|
|
2018
|
+
if (this.writeBuffer.byteLength === 0) {
|
|
2019
|
+
this.log.trace("not processing send queue as no bytes to send");
|
|
2020
|
+
return true;
|
|
2021
|
+
}
|
|
2022
|
+
if (this.sendingData) {
|
|
2023
|
+
this.log.trace("not processing send queue as already sending data");
|
|
2024
|
+
return true;
|
|
2025
|
+
}
|
|
2026
|
+
this.sendingData = true;
|
|
2027
|
+
this.log.trace("processing send queue with %d queued bytes", this.writeBuffer.byteLength);
|
|
2028
|
+
try {
|
|
2029
|
+
let canSendMore = true;
|
|
2030
|
+
const totalBytes = this.writeBuffer.byteLength;
|
|
2031
|
+
let sentBytes = 0;
|
|
2032
|
+
while (this.writeBuffer.byteLength > 0) {
|
|
2033
|
+
const end = Math.min(this.maxMessageSize ?? this.writeBuffer.byteLength, this.writeBuffer.byteLength);
|
|
2034
|
+
if (end === 0) {
|
|
2035
|
+
canSendMore = false;
|
|
2036
|
+
break;
|
|
2037
|
+
}
|
|
2038
|
+
const toSend = this.writeBuffer.sublist(0, end);
|
|
2039
|
+
const willSend = new Uint8ArrayList(toSend);
|
|
2040
|
+
this.writeBuffer.consume(toSend.byteLength);
|
|
2041
|
+
const sendResult = this.sendData(toSend);
|
|
2042
|
+
canSendMore = sendResult.canSendMore;
|
|
2043
|
+
sentBytes += sendResult.sentBytes;
|
|
2044
|
+
if (sendResult.sentBytes !== willSend.byteLength) {
|
|
2045
|
+
willSend.consume(sendResult.sentBytes);
|
|
2046
|
+
this.writeBuffer.prepend(willSend);
|
|
2047
|
+
}
|
|
2048
|
+
if (!canSendMore) {
|
|
2049
|
+
break;
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
if (!canSendMore) {
|
|
2053
|
+
this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer", sentBytes, totalBytes, this.writeBuffer.byteLength);
|
|
2054
|
+
this.writableNeedsDrain = true;
|
|
2055
|
+
this.checkWriteBufferLength();
|
|
2056
|
+
}
|
|
2057
|
+
if (this.writeBuffer.byteLength === 0) {
|
|
2058
|
+
this.safeDispatchEvent("idle");
|
|
2059
|
+
}
|
|
2060
|
+
return canSendMore;
|
|
2061
|
+
} finally {
|
|
2062
|
+
this.sendingData = false;
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
dispatchReadBuffer() {
|
|
2066
|
+
try {
|
|
2067
|
+
if (this.listenerCount("message") === 0) {
|
|
2068
|
+
this.log.trace("not dispatching pause buffer as there are no listeners for the message event");
|
|
2069
|
+
return;
|
|
2070
|
+
}
|
|
2071
|
+
if (this.readBuffer.byteLength === 0) {
|
|
2072
|
+
this.log.trace("not dispatching pause buffer as there is no data to dispatch");
|
|
2073
|
+
return;
|
|
2074
|
+
}
|
|
2075
|
+
if (this.readStatus === "paused") {
|
|
2076
|
+
this.log.trace("not dispatching pause buffer we are paused");
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
if (this.readStatus === "closing" || this.readStatus === "closed") {
|
|
2080
|
+
this.log("dropping %d bytes because the readable end is %s", this.readBuffer.byteLength, this.readStatus);
|
|
2081
|
+
this.readBuffer.consume(this.readBuffer.byteLength);
|
|
2082
|
+
return;
|
|
2083
|
+
}
|
|
2084
|
+
const buf = this.readBuffer.sublist();
|
|
2085
|
+
this.readBuffer.consume(buf.byteLength);
|
|
2086
|
+
this.dispatchEvent(new StreamMessageEvent(buf));
|
|
2087
|
+
} finally {
|
|
2088
|
+
if (this.readBuffer.byteLength === 0 && this.remoteWriteStatus === "closed") {
|
|
2089
|
+
this.log("close readable end after dispatching read buffer and remote writable end is closed");
|
|
2090
|
+
this.readStatus = "closed";
|
|
2091
|
+
}
|
|
2092
|
+
this.checkReadBufferLength();
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
checkReadBufferLength() {
|
|
2096
|
+
if (this.readBuffer.byteLength > this.maxReadBufferLength) {
|
|
2097
|
+
this.abort(new StreamBufferError(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`));
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
checkWriteBufferLength() {
|
|
2101
|
+
if (this.maxWriteBufferLength == null) {
|
|
2102
|
+
return;
|
|
2103
|
+
}
|
|
2104
|
+
if (this.writeBuffer.byteLength > this.maxWriteBufferLength) {
|
|
2105
|
+
this.abort(new StreamBufferError(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`));
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
onMuxerNeedsDrain() {
|
|
2109
|
+
this.writableNeedsDrain = true;
|
|
2110
|
+
}
|
|
2111
|
+
onMuxerDrain() {
|
|
2112
|
+
this.safeDispatchEvent("drain");
|
|
2113
|
+
}
|
|
2114
|
+
};
|
|
2115
|
+
|
|
2116
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/abstract-multiaddr-connection.js
|
|
2117
|
+
init_esm_shims();
|
|
2118
|
+
var AbstractMultiaddrConnection = class extends AbstractMessageStream {
|
|
2119
|
+
remoteAddr;
|
|
2120
|
+
metricPrefix;
|
|
2121
|
+
metrics;
|
|
2122
|
+
constructor(init) {
|
|
2123
|
+
super(init);
|
|
2124
|
+
this.metricPrefix = init.metricPrefix ?? "";
|
|
2125
|
+
this.metrics = init.metrics;
|
|
2126
|
+
this.remoteAddr = init.remoteAddr;
|
|
2127
|
+
this.addEventListener("close", (evt) => {
|
|
2128
|
+
this.metrics?.increment({ [`${this.metricPrefix}end`]: true });
|
|
2129
|
+
if (evt.error != null) {
|
|
2130
|
+
if (evt.local) {
|
|
2131
|
+
this.metrics?.increment({ [`${this.metricPrefix}abort`]: true });
|
|
2132
|
+
} else {
|
|
2133
|
+
this.metrics?.increment({ [`${this.metricPrefix}reset`]: true });
|
|
2134
|
+
}
|
|
2135
|
+
} else {
|
|
2136
|
+
if (evt.local) {
|
|
2137
|
+
this.metrics?.increment({ [`${this.metricPrefix}_local_close`]: true });
|
|
2138
|
+
} else {
|
|
2139
|
+
this.metrics?.increment({ [`${this.metricPrefix}_remote_close`]: true });
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
});
|
|
2143
|
+
}
|
|
2144
|
+
async close(options) {
|
|
2145
|
+
if (this.status !== "open") {
|
|
2146
|
+
return;
|
|
2147
|
+
}
|
|
2148
|
+
this.status = "closing";
|
|
2149
|
+
this.writeStatus = "closing";
|
|
2150
|
+
this.remoteWriteStatus = "closing";
|
|
2151
|
+
this.remoteReadStatus = "closing";
|
|
2152
|
+
if (this.sendingData || this.writeBuffer.byteLength > 0) {
|
|
2153
|
+
this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes", this.writeBuffer.byteLength);
|
|
2154
|
+
await pEvent(this, "idle", {
|
|
2155
|
+
...options,
|
|
2156
|
+
rejectionEvents: [
|
|
2157
|
+
"close"
|
|
2158
|
+
]
|
|
2159
|
+
});
|
|
2160
|
+
}
|
|
2161
|
+
if (this.writableNeedsDrain) {
|
|
2162
|
+
this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes", this.writeBuffer.byteLength);
|
|
2163
|
+
await pEvent(this, "drain", {
|
|
2164
|
+
...options,
|
|
2165
|
+
rejectionEvents: [
|
|
2166
|
+
"close"
|
|
2167
|
+
]
|
|
2168
|
+
});
|
|
2169
|
+
}
|
|
2170
|
+
await this.sendClose(options);
|
|
2171
|
+
this.onTransportClosed();
|
|
2172
|
+
}
|
|
2173
|
+
};
|
|
2174
|
+
|
|
2175
|
+
// ../../node_modules/.pnpm/any-signal@4.2.0/node_modules/any-signal/dist/src/index.js
|
|
2176
|
+
init_esm_shims();
|
|
2177
|
+
function anySignal(signals) {
|
|
2178
|
+
const controller = new globalThis.AbortController();
|
|
2179
|
+
function onAbort() {
|
|
2180
|
+
const reason = signals.filter((s) => s?.aborted === true).map((s) => s?.reason).pop();
|
|
2181
|
+
controller.abort(reason);
|
|
2182
|
+
for (const signal2 of signals) {
|
|
2183
|
+
if (signal2?.removeEventListener != null) {
|
|
2184
|
+
signal2.removeEventListener("abort", onAbort);
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
for (const signal2 of signals) {
|
|
2189
|
+
if (signal2?.aborted === true) {
|
|
2190
|
+
onAbort();
|
|
2191
|
+
break;
|
|
2192
|
+
}
|
|
2193
|
+
if (signal2?.addEventListener != null) {
|
|
2194
|
+
signal2.addEventListener("abort", onAbort);
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
function clear() {
|
|
2198
|
+
for (const signal2 of signals) {
|
|
2199
|
+
if (signal2?.removeEventListener != null) {
|
|
2200
|
+
signal2.removeEventListener("abort", onAbort);
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
const signal = controller.signal;
|
|
2205
|
+
signal.clear = clear;
|
|
2206
|
+
return signal;
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2209
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/get-thin-waist-addresses.js
|
|
2210
|
+
init_esm_shims();
|
|
2211
|
+
|
|
2212
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/link-local-ip.js
|
|
2213
|
+
init_esm_shims();
|
|
2214
|
+
function isLinkLocalIp(ip) {
|
|
2215
|
+
if (ip.startsWith("169.254.")) {
|
|
2216
|
+
return true;
|
|
2217
|
+
}
|
|
2218
|
+
if (ip.toLowerCase().startsWith("fe80")) {
|
|
2219
|
+
return true;
|
|
2220
|
+
}
|
|
2221
|
+
return false;
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/multiaddr/utils.js
|
|
2225
|
+
init_esm_shims();
|
|
2226
|
+
function netConfigToMultiaddr(config, port, host) {
|
|
2227
|
+
const parts = [
|
|
2228
|
+
config.type,
|
|
2229
|
+
host ?? config.host
|
|
2230
|
+
];
|
|
2231
|
+
if (config.protocol != null) {
|
|
2232
|
+
const p = port ?? config.port;
|
|
2233
|
+
if (p != null) {
|
|
2234
|
+
parts.push(config.protocol, p);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
if (config.type === "ip6" && config.zone != null) {
|
|
2238
|
+
parts.unshift("ip6zone", config.zone);
|
|
2239
|
+
}
|
|
2240
|
+
if (config.cidr != null) {
|
|
2241
|
+
parts.push("ipcidr", config.cidr);
|
|
2242
|
+
}
|
|
2243
|
+
return multiaddr(`/${parts.join("/")}`);
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/get-thin-waist-addresses.js
|
|
2247
|
+
var FAMILIES = { 4: "IPv4", 6: "IPv6" };
|
|
2248
|
+
function isWildcard(ip) {
|
|
2249
|
+
return ["0.0.0.0", "::"].includes(ip);
|
|
2250
|
+
}
|
|
2251
|
+
function getNetworkAddrs(family) {
|
|
2252
|
+
const addresses = [];
|
|
2253
|
+
const networks = os.networkInterfaces();
|
|
2254
|
+
for (const [, netAddrs] of Object.entries(networks)) {
|
|
2255
|
+
if (netAddrs != null) {
|
|
2256
|
+
for (const netAddr of netAddrs) {
|
|
2257
|
+
if (isLinkLocalIp(netAddr.address)) {
|
|
2258
|
+
continue;
|
|
2259
|
+
}
|
|
2260
|
+
if (netAddr.family === FAMILIES[family]) {
|
|
2261
|
+
addresses.push(netAddr.address);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
return addresses;
|
|
2267
|
+
}
|
|
2268
|
+
function getThinWaistAddresses(ma, port) {
|
|
2269
|
+
if (ma == null) {
|
|
2270
|
+
return [];
|
|
2271
|
+
}
|
|
2272
|
+
const config = getNetConfig(ma);
|
|
2273
|
+
if ((config.type === "ip4" || config.type === "ip6") && isWildcard(config.host)) {
|
|
2274
|
+
return getNetworkAddrs(config.type === "ip4" ? 4 : 6).map((host) => netConfigToMultiaddr(config, port, host));
|
|
2275
|
+
}
|
|
2276
|
+
return [
|
|
2277
|
+
netConfigToMultiaddr(config, port)
|
|
2278
|
+
];
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/ip-port-to-multiaddr.js
|
|
2282
|
+
init_esm_shims();
|
|
2283
|
+
function ipPortToMultiaddr(ip, port) {
|
|
2284
|
+
if (typeof ip !== "string") {
|
|
2285
|
+
throw new InvalidParametersError(`invalid ip provided: ${ip}`);
|
|
2286
|
+
}
|
|
2287
|
+
if (typeof port === "string") {
|
|
2288
|
+
port = parseInt(port);
|
|
2289
|
+
}
|
|
2290
|
+
if (isNaN(port)) {
|
|
2291
|
+
throw new InvalidParametersError(`invalid port provided: ${port}`);
|
|
2292
|
+
}
|
|
2293
|
+
if (isIPv4(ip)) {
|
|
2294
|
+
return multiaddr(`/ip4/${ip}/tcp/${port}`);
|
|
2295
|
+
}
|
|
2296
|
+
if (isIPv6(ip)) {
|
|
2297
|
+
return multiaddr(`/ip6/${ip}/tcp/${port}`);
|
|
2298
|
+
}
|
|
2299
|
+
throw new InvalidParametersError(`invalid ip:port for creating a multiaddr: ${ip}:${port}`);
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
// ../../node_modules/.pnpm/@libp2p+utils@7.0.12/node_modules/@libp2p/utils/dist/src/repeating-task.js
|
|
2303
|
+
init_esm_shims();
|
|
2304
|
+
function repeatingTask(fn, interval, options) {
|
|
2305
|
+
let timeout;
|
|
2306
|
+
let shutdownController;
|
|
2307
|
+
let running = false;
|
|
2308
|
+
function runTask() {
|
|
2309
|
+
const opts = {
|
|
2310
|
+
signal: shutdownController.signal
|
|
2311
|
+
};
|
|
2312
|
+
if (options?.timeout != null) {
|
|
2313
|
+
const signal = anySignal([shutdownController.signal, AbortSignal.timeout(options.timeout)]);
|
|
2314
|
+
setMaxListeners(Infinity, signal);
|
|
2315
|
+
opts.signal = signal;
|
|
2316
|
+
}
|
|
2317
|
+
running = true;
|
|
2318
|
+
Promise.resolve().then(async () => {
|
|
2319
|
+
await fn(opts);
|
|
2320
|
+
}).catch(() => {
|
|
2321
|
+
}).finally(() => {
|
|
2322
|
+
running = false;
|
|
2323
|
+
if (shutdownController.signal.aborted) {
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
timeout = setTimeout(runTask, interval);
|
|
2327
|
+
});
|
|
2328
|
+
}
|
|
2329
|
+
const runTaskDebounced = debounce(runTask, options?.debounce ?? 100);
|
|
2330
|
+
let started = false;
|
|
2331
|
+
return {
|
|
2332
|
+
setInterval: (ms) => {
|
|
2333
|
+
if (interval === ms) {
|
|
2334
|
+
return;
|
|
2335
|
+
}
|
|
2336
|
+
interval = ms;
|
|
2337
|
+
if (timeout != null) {
|
|
2338
|
+
clearTimeout(timeout);
|
|
2339
|
+
timeout = setTimeout(runTask, interval);
|
|
2340
|
+
}
|
|
2341
|
+
},
|
|
2342
|
+
setTimeout: (ms) => {
|
|
2343
|
+
options ??= {};
|
|
2344
|
+
options.timeout = ms;
|
|
2345
|
+
},
|
|
2346
|
+
run: () => {
|
|
2347
|
+
if (running) {
|
|
2348
|
+
return;
|
|
2349
|
+
}
|
|
2350
|
+
clearTimeout(timeout);
|
|
2351
|
+
runTaskDebounced();
|
|
2352
|
+
},
|
|
2353
|
+
start: () => {
|
|
2354
|
+
if (started) {
|
|
2355
|
+
return;
|
|
2356
|
+
}
|
|
2357
|
+
started = true;
|
|
2358
|
+
shutdownController = new AbortController();
|
|
2359
|
+
setMaxListeners(Infinity, shutdownController.signal);
|
|
2360
|
+
if (options?.runImmediately === true) {
|
|
2361
|
+
queueMicrotask(() => {
|
|
2362
|
+
runTask();
|
|
2363
|
+
});
|
|
2364
|
+
} else {
|
|
2365
|
+
timeout = setTimeout(runTask, interval);
|
|
2366
|
+
}
|
|
2367
|
+
},
|
|
2368
|
+
stop: () => {
|
|
2369
|
+
clearTimeout(timeout);
|
|
2370
|
+
shutdownController?.abort();
|
|
2371
|
+
started = false;
|
|
2372
|
+
}
|
|
2373
|
+
};
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
// ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/utils.js
|
|
2377
|
+
init_esm_shims();
|
|
2378
|
+
function toWebSocket(ws2) {
|
|
2379
|
+
Object.defineProperty(ws2, "url", {
|
|
2380
|
+
value: "",
|
|
2381
|
+
writable: false
|
|
2382
|
+
});
|
|
2383
|
+
ws2.dispatchEvent = (evt) => {
|
|
2384
|
+
if (evt.type === "close") {
|
|
2385
|
+
ws2.emit("close");
|
|
2386
|
+
}
|
|
2387
|
+
if (evt.type === "open") {
|
|
2388
|
+
ws2.emit("open");
|
|
2389
|
+
}
|
|
2390
|
+
if (evt.type === "message") {
|
|
2391
|
+
const m = evt;
|
|
2392
|
+
ws2.emit("data", m.data);
|
|
2393
|
+
}
|
|
2394
|
+
if (evt.type === "error") {
|
|
2395
|
+
ws2.emit("error", new Error("An error occurred"));
|
|
2396
|
+
}
|
|
2397
|
+
ws2.emit(evt.type, evt);
|
|
2398
|
+
};
|
|
2399
|
+
return ws2;
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/websocket-to-conn.js
|
|
2403
|
+
init_esm_shims();
|
|
2404
|
+
var DEFAULT_MAX_BUFFERED_AMOUNT = 1024 * 1024 * 4;
|
|
2405
|
+
var DEFAULT_BUFFERED_AMOUNT_POLL_INTERVAL = 10;
|
|
2406
|
+
var WebSocketMultiaddrConnection = class extends AbstractMultiaddrConnection {
|
|
2407
|
+
websocket;
|
|
2408
|
+
maxBufferedAmount;
|
|
2409
|
+
checkBufferedAmountTask;
|
|
2410
|
+
constructor(init) {
|
|
2411
|
+
super(init);
|
|
2412
|
+
this.websocket = init.websocket;
|
|
2413
|
+
this.maxBufferedAmount = init.maxBufferedAmount ?? DEFAULT_MAX_BUFFERED_AMOUNT;
|
|
2414
|
+
this.checkBufferedAmountTask = repeatingTask(this.checkBufferedAmount.bind(this), init.bufferedAmountPollInterval ?? DEFAULT_BUFFERED_AMOUNT_POLL_INTERVAL);
|
|
2415
|
+
this.websocket.addEventListener("close", (evt) => {
|
|
2416
|
+
this.log('closed - code %d, reason "%s", wasClean %s', evt.code, evt.reason, evt.wasClean);
|
|
2417
|
+
this.checkBufferedAmountTask.stop();
|
|
2418
|
+
if (!evt.wasClean) {
|
|
2419
|
+
this.onRemoteReset();
|
|
2420
|
+
return;
|
|
2421
|
+
}
|
|
2422
|
+
this.onTransportClosed();
|
|
2423
|
+
}, { once: true });
|
|
2424
|
+
this.websocket.addEventListener("message", (evt) => {
|
|
2425
|
+
try {
|
|
2426
|
+
let buf;
|
|
2427
|
+
if (typeof evt.data === "string") {
|
|
2428
|
+
buf = fromString(evt.data);
|
|
2429
|
+
} else if (evt.data instanceof ArrayBuffer) {
|
|
2430
|
+
buf = new Uint8Array(evt.data, 0, evt.data.byteLength);
|
|
2431
|
+
} else {
|
|
2432
|
+
this.abort(new Error("Incorrect binary type"));
|
|
2433
|
+
return;
|
|
2434
|
+
}
|
|
2435
|
+
this.onData(buf);
|
|
2436
|
+
} catch (err) {
|
|
2437
|
+
this.log.error("error receiving data - %e", err);
|
|
2438
|
+
}
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
sendData(data) {
|
|
2442
|
+
for (const buf of data) {
|
|
2443
|
+
this.websocket.send(buf);
|
|
2444
|
+
}
|
|
2445
|
+
const canSendMore = this.websocket.bufferedAmount < this.maxBufferedAmount;
|
|
2446
|
+
if (!canSendMore) {
|
|
2447
|
+
this.checkBufferedAmountTask.start();
|
|
2448
|
+
}
|
|
2449
|
+
return {
|
|
2450
|
+
sentBytes: data.byteLength,
|
|
2451
|
+
canSendMore
|
|
2452
|
+
};
|
|
2453
|
+
}
|
|
2454
|
+
sendReset() {
|
|
2455
|
+
this.websocket.close(1006);
|
|
2456
|
+
}
|
|
2457
|
+
async sendClose(options) {
|
|
2458
|
+
this.websocket.close();
|
|
2459
|
+
options?.signal?.throwIfAborted();
|
|
2460
|
+
}
|
|
2461
|
+
sendPause() {
|
|
2462
|
+
}
|
|
2463
|
+
sendResume() {
|
|
2464
|
+
}
|
|
2465
|
+
checkBufferedAmount() {
|
|
2466
|
+
this.log("buffered amount now %d", this.websocket.bufferedAmount);
|
|
2467
|
+
if (this.websocket.bufferedAmount === 0) {
|
|
2468
|
+
this.checkBufferedAmountTask.stop();
|
|
2469
|
+
this.safeDispatchEvent("drain");
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
};
|
|
2473
|
+
function webSocketToMaConn(init) {
|
|
2474
|
+
return new WebSocketMultiaddrConnection(init);
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
// ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/listener.js
|
|
2478
|
+
var WebSocketListener = class extends TypedEventEmitter {
|
|
2479
|
+
components;
|
|
2480
|
+
log;
|
|
2481
|
+
server;
|
|
2482
|
+
wsServer;
|
|
2483
|
+
metrics;
|
|
2484
|
+
sockets;
|
|
2485
|
+
upgrader;
|
|
2486
|
+
httpOptions;
|
|
2487
|
+
httpsOptions;
|
|
2488
|
+
shutdownController;
|
|
2489
|
+
http;
|
|
2490
|
+
https;
|
|
2491
|
+
addr;
|
|
2492
|
+
listeningMultiaddr;
|
|
2493
|
+
maxBufferedAmount;
|
|
2494
|
+
bufferedAmountPollInterval;
|
|
2495
|
+
constructor(components, init) {
|
|
2496
|
+
super();
|
|
2497
|
+
this.components = components;
|
|
2498
|
+
this.log = components.logger.forComponent("libp2p:websockets:listener");
|
|
2499
|
+
this.upgrader = init.upgrader;
|
|
2500
|
+
this.httpOptions = init.http;
|
|
2501
|
+
this.httpsOptions = init.https ?? init.http;
|
|
2502
|
+
this.maxBufferedAmount = init.maxBufferedAmount;
|
|
2503
|
+
this.bufferedAmountPollInterval = init.bufferedAmountPollInterval;
|
|
2504
|
+
this.sockets = /* @__PURE__ */ new Set();
|
|
2505
|
+
this.shutdownController = new AbortController();
|
|
2506
|
+
setMaxListeners(Infinity, this.shutdownController.signal);
|
|
2507
|
+
this.wsServer = new ws.WebSocketServer({
|
|
2508
|
+
noServer: true
|
|
2509
|
+
});
|
|
2510
|
+
this.wsServer.addListener("connection", this.onWsServerConnection.bind(this));
|
|
2511
|
+
components.metrics?.registerMetricGroup("libp2p_websockets_inbound_connections_total", {
|
|
2512
|
+
label: "address",
|
|
2513
|
+
help: "Current active connections in WebSocket listener",
|
|
2514
|
+
calculate: () => {
|
|
2515
|
+
if (this.addr == null) {
|
|
2516
|
+
return {};
|
|
2517
|
+
}
|
|
2518
|
+
return {
|
|
2519
|
+
[this.addr]: this.sockets.size
|
|
2520
|
+
};
|
|
2521
|
+
}
|
|
2522
|
+
});
|
|
2523
|
+
this.metrics = {
|
|
2524
|
+
status: components.metrics?.registerMetricGroup("libp2p_websockets_listener_status_info", {
|
|
2525
|
+
label: "address",
|
|
2526
|
+
help: "Current status of the WebSocket listener socket"
|
|
2527
|
+
}),
|
|
2528
|
+
errors: components.metrics?.registerMetricGroup("libp2p_websockets_listener_errors_total", {
|
|
2529
|
+
label: "address",
|
|
2530
|
+
help: "Total count of WebSocket listener errors by type"
|
|
2531
|
+
}),
|
|
2532
|
+
events: components.metrics?.registerMetricGroup("libp2p_websockets_listener_events_total", {
|
|
2533
|
+
label: "address",
|
|
2534
|
+
help: "Total count of WebSocket listener events by type"
|
|
2535
|
+
})
|
|
2536
|
+
};
|
|
2537
|
+
this.server = net.createServer({
|
|
2538
|
+
pauseOnConnect: true
|
|
2539
|
+
}, (socket) => {
|
|
2540
|
+
this.onSocketConnection(socket).catch((err) => {
|
|
2541
|
+
this.log.error("error handling socket - %e", err);
|
|
2542
|
+
socket.destroy();
|
|
2543
|
+
});
|
|
2544
|
+
});
|
|
2545
|
+
components.events.addEventListener("certificate:provision", this.onCertificateProvision.bind(this));
|
|
2546
|
+
components.events.addEventListener("certificate:renew", this.onCertificateRenew.bind(this));
|
|
2547
|
+
}
|
|
2548
|
+
async onSocketConnection(socket) {
|
|
2549
|
+
this.metrics.events?.increment({ [`${this.addr} connection`]: true });
|
|
2550
|
+
let buffer = socket.read(1);
|
|
2551
|
+
if (buffer == null) {
|
|
2552
|
+
await pEvent(socket, "readable");
|
|
2553
|
+
buffer = socket.read(1);
|
|
2554
|
+
}
|
|
2555
|
+
const byte = buffer[0];
|
|
2556
|
+
let server = this.http;
|
|
2557
|
+
if (byte < 32 || byte >= 127) {
|
|
2558
|
+
server = this.https;
|
|
2559
|
+
}
|
|
2560
|
+
if (server == null) {
|
|
2561
|
+
this.log.error("no appropriate listener configured for byte %d", byte);
|
|
2562
|
+
socket.destroy();
|
|
2563
|
+
return;
|
|
2564
|
+
}
|
|
2565
|
+
this.sockets.add(socket);
|
|
2566
|
+
socket.on("close", () => {
|
|
2567
|
+
this.metrics.events?.increment({ [`${this.addr} close`]: true });
|
|
2568
|
+
this.sockets.delete(socket);
|
|
2569
|
+
});
|
|
2570
|
+
socket.on("error", (err) => {
|
|
2571
|
+
this.log.error("socket error - %e", err);
|
|
2572
|
+
this.metrics.events?.increment({ [`${this.addr} error`]: true });
|
|
2573
|
+
socket.destroy();
|
|
2574
|
+
});
|
|
2575
|
+
socket.once("timeout", () => {
|
|
2576
|
+
this.metrics.events?.increment({ [`${this.addr} timeout`]: true });
|
|
2577
|
+
});
|
|
2578
|
+
socket.once("end", () => {
|
|
2579
|
+
this.metrics.events?.increment({ [`${this.addr} end`]: true });
|
|
2580
|
+
});
|
|
2581
|
+
socket.unshift(buffer);
|
|
2582
|
+
server.emit("connection", socket);
|
|
2583
|
+
}
|
|
2584
|
+
onWsServerConnection(socket, req) {
|
|
2585
|
+
let addr;
|
|
2586
|
+
socket.binaryType = "arraybuffer";
|
|
2587
|
+
try {
|
|
2588
|
+
addr = this.server.address();
|
|
2589
|
+
if (typeof addr === "string") {
|
|
2590
|
+
throw new Error("Cannot listen on unix sockets");
|
|
2591
|
+
}
|
|
2592
|
+
if (addr == null) {
|
|
2593
|
+
throw new Error("Server was closing or not running");
|
|
2594
|
+
}
|
|
2595
|
+
} catch (err) {
|
|
2596
|
+
this.log.error("error obtaining remote socket address - %e", err);
|
|
2597
|
+
req.destroy(err);
|
|
2598
|
+
socket.close();
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
let maConn;
|
|
2602
|
+
try {
|
|
2603
|
+
maConn = webSocketToMaConn({
|
|
2604
|
+
websocket: toWebSocket(socket),
|
|
2605
|
+
remoteAddr: ipPortToMultiaddr(req.socket.remoteAddress ?? "0.0.0.0", req.socket.remotePort ?? 0).encapsulate("/ws"),
|
|
2606
|
+
metrics: this.metrics?.events,
|
|
2607
|
+
metricPrefix: `${this.addr} `,
|
|
2608
|
+
direction: "inbound",
|
|
2609
|
+
log: this.components.logger.forComponent("libp2p:websockets:connection"),
|
|
2610
|
+
maxBufferedAmount: this.maxBufferedAmount,
|
|
2611
|
+
bufferedAmountPollInterval: this.bufferedAmountPollInterval
|
|
2612
|
+
});
|
|
2613
|
+
} catch (err) {
|
|
2614
|
+
this.log.error("inbound connection failed - %e", err);
|
|
2615
|
+
this.metrics.errors?.increment({ [`${this.addr} inbound_to_connection`]: true });
|
|
2616
|
+
socket.close();
|
|
2617
|
+
return;
|
|
2618
|
+
}
|
|
2619
|
+
this.log("new inbound connection %s", maConn.remoteAddr);
|
|
2620
|
+
this.upgrader.upgradeInbound(maConn, {
|
|
2621
|
+
signal: this.shutdownController.signal
|
|
2622
|
+
}).catch(async (err) => {
|
|
2623
|
+
this.log.error("inbound connection failed to upgrade - %e", err);
|
|
2624
|
+
this.metrics.errors?.increment({ [`${this.addr} inbound_upgrade`]: true });
|
|
2625
|
+
maConn.close();
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
onUpgrade(req, socket, head) {
|
|
2629
|
+
this.wsServer.handleUpgrade(req, socket, head, this.onWsServerConnection.bind(this));
|
|
2630
|
+
}
|
|
2631
|
+
onTLSClientError(err, socket) {
|
|
2632
|
+
this.log.error("TLS client error - %e", err);
|
|
2633
|
+
socket.destroy();
|
|
2634
|
+
}
|
|
2635
|
+
async listen(ma) {
|
|
2636
|
+
if (WebSockets.exactMatch(ma)) {
|
|
2637
|
+
this.http = http.createServer(this.httpOptions ?? {}, this.httpRequestHandler.bind(this));
|
|
2638
|
+
this.http.addListener("upgrade", this.onUpgrade.bind(this));
|
|
2639
|
+
} else if (WebSocketsSecure.exactMatch(ma)) {
|
|
2640
|
+
this.https = https.createServer(this.httpsOptions ?? {}, this.httpRequestHandler.bind(this));
|
|
2641
|
+
this.https.addListener("upgrade", this.onUpgrade.bind(this));
|
|
2642
|
+
this.https.addListener("tlsClientError", this.onTLSClientError.bind(this));
|
|
2643
|
+
}
|
|
2644
|
+
const config = getNetConfig(ma);
|
|
2645
|
+
this.addr = `${config.host}:${config.port}`;
|
|
2646
|
+
this.server.listen({
|
|
2647
|
+
...config,
|
|
2648
|
+
ipv6Only: config.type === "ip6"
|
|
2649
|
+
});
|
|
2650
|
+
await new Promise((resolve, reject) => {
|
|
2651
|
+
const onListening = () => {
|
|
2652
|
+
removeListeners();
|
|
2653
|
+
resolve();
|
|
2654
|
+
};
|
|
2655
|
+
const onError = (err) => {
|
|
2656
|
+
this.metrics.errors?.increment({ [`${this.addr} listen_error`]: true });
|
|
2657
|
+
removeListeners();
|
|
2658
|
+
reject(err);
|
|
2659
|
+
};
|
|
2660
|
+
const onDrop = () => {
|
|
2661
|
+
this.metrics.events?.increment({ [`${this.addr} drop`]: true });
|
|
2662
|
+
};
|
|
2663
|
+
const removeListeners = () => {
|
|
2664
|
+
this.server.removeListener("listening", onListening);
|
|
2665
|
+
this.server.removeListener("error", onError);
|
|
2666
|
+
this.server.removeListener("drop", onDrop);
|
|
2667
|
+
};
|
|
2668
|
+
this.server.addListener("listening", onListening);
|
|
2669
|
+
this.server.addListener("error", onError);
|
|
2670
|
+
this.server.addListener("drop", onDrop);
|
|
2671
|
+
});
|
|
2672
|
+
this.listeningMultiaddr = ma;
|
|
2673
|
+
this.safeDispatchEvent("listening");
|
|
2674
|
+
}
|
|
2675
|
+
onCertificateProvision(event) {
|
|
2676
|
+
if (this.https != null) {
|
|
2677
|
+
this.log("auto-tls certificate found but already listening on https");
|
|
2678
|
+
return;
|
|
2679
|
+
}
|
|
2680
|
+
this.log("auto-tls certificate found, starting https server");
|
|
2681
|
+
this.https = https.createServer({
|
|
2682
|
+
...this.httpsOptions,
|
|
2683
|
+
...event.detail
|
|
2684
|
+
}, this.httpRequestHandler.bind(this));
|
|
2685
|
+
this.https.addListener("upgrade", this.onUpgrade.bind(this));
|
|
2686
|
+
this.https.addListener("tlsClientError", this.onTLSClientError.bind(this));
|
|
2687
|
+
this.safeDispatchEvent("listening");
|
|
2688
|
+
}
|
|
2689
|
+
onCertificateRenew(event) {
|
|
2690
|
+
this.https?.close();
|
|
2691
|
+
this.log("auto-tls certificate renewed, restarting https server");
|
|
2692
|
+
this.https = https.createServer({
|
|
2693
|
+
...this.httpsOptions,
|
|
2694
|
+
...event.detail
|
|
2695
|
+
}, this.httpRequestHandler.bind(this));
|
|
2696
|
+
this.https.addListener("upgrade", this.onUpgrade.bind(this));
|
|
2697
|
+
this.https.addListener("tlsClientError", this.onTLSClientError.bind(this));
|
|
2698
|
+
}
|
|
2699
|
+
async close() {
|
|
2700
|
+
this.server.close();
|
|
2701
|
+
this.http?.close();
|
|
2702
|
+
this.https?.close();
|
|
2703
|
+
this.wsServer.close();
|
|
2704
|
+
this.http?.closeAllConnections();
|
|
2705
|
+
this.https?.closeAllConnections();
|
|
2706
|
+
[...this.sockets].forEach((socket) => {
|
|
2707
|
+
socket.destroy();
|
|
2708
|
+
});
|
|
2709
|
+
this.shutdownController.abort();
|
|
2710
|
+
const events = [
|
|
2711
|
+
pEvent(this.server, "close"),
|
|
2712
|
+
pEvent(this.wsServer, "close")
|
|
2713
|
+
];
|
|
2714
|
+
if (this.http != null) {
|
|
2715
|
+
events.push(pEvent(this.http, "close"));
|
|
2716
|
+
}
|
|
2717
|
+
if (this.https != null) {
|
|
2718
|
+
events.push(pEvent(this.https, "close"));
|
|
2719
|
+
}
|
|
2720
|
+
await Promise.all(events);
|
|
2721
|
+
this.safeDispatchEvent("close");
|
|
2722
|
+
}
|
|
2723
|
+
getAddrs() {
|
|
2724
|
+
const address = this.server.address();
|
|
2725
|
+
if (address == null) {
|
|
2726
|
+
return [];
|
|
2727
|
+
}
|
|
2728
|
+
if (typeof address === "string") {
|
|
2729
|
+
return [multiaddr(`/unix/${encodeURIComponent(address)}/ws`)];
|
|
2730
|
+
}
|
|
2731
|
+
const multiaddrs = getThinWaistAddresses(this.listeningMultiaddr, address.port);
|
|
2732
|
+
const insecureMultiaddrs = [];
|
|
2733
|
+
if (this.http != null) {
|
|
2734
|
+
multiaddrs.forEach((ma) => {
|
|
2735
|
+
insecureMultiaddrs.push(ma.encapsulate("/ws"));
|
|
2736
|
+
});
|
|
2737
|
+
}
|
|
2738
|
+
const secureMultiaddrs = [];
|
|
2739
|
+
if (this.https != null) {
|
|
2740
|
+
multiaddrs.forEach((ma) => {
|
|
2741
|
+
secureMultiaddrs.push(ma.encapsulate("/tls/ws"));
|
|
2742
|
+
});
|
|
2743
|
+
}
|
|
2744
|
+
return [
|
|
2745
|
+
...insecureMultiaddrs,
|
|
2746
|
+
...secureMultiaddrs
|
|
2747
|
+
];
|
|
2748
|
+
}
|
|
2749
|
+
updateAnnounceAddrs() {
|
|
121
2750
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
} catch {
|
|
127
|
-
return false;
|
|
2751
|
+
httpRequestHandler(req, res) {
|
|
2752
|
+
res.writeHead(400);
|
|
2753
|
+
res.write("Only WebSocket connections are supported");
|
|
2754
|
+
res.end();
|
|
128
2755
|
}
|
|
2756
|
+
};
|
|
2757
|
+
function createListener(components, init) {
|
|
2758
|
+
return new WebSocketListener(components, init);
|
|
129
2759
|
}
|
|
130
2760
|
|
|
131
|
-
// src/
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
2761
|
+
// ../../node_modules/.pnpm/@libp2p+websockets@10.1.5/node_modules/@libp2p/websockets/dist/src/index.js
|
|
2762
|
+
var WebSockets2 = class {
|
|
2763
|
+
log;
|
|
2764
|
+
init;
|
|
2765
|
+
logger;
|
|
2766
|
+
metrics;
|
|
2767
|
+
components;
|
|
2768
|
+
constructor(components, init = {}) {
|
|
2769
|
+
this.log = components.logger.forComponent("libp2p:websockets");
|
|
2770
|
+
this.logger = components.logger;
|
|
2771
|
+
this.components = components;
|
|
2772
|
+
this.init = init;
|
|
2773
|
+
if (components.metrics != null) {
|
|
2774
|
+
this.metrics = {
|
|
2775
|
+
dialerEvents: components.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total", {
|
|
2776
|
+
label: "event",
|
|
2777
|
+
help: "Total count of WebSockets dialer events by type"
|
|
2778
|
+
})
|
|
2779
|
+
};
|
|
2780
|
+
}
|
|
143
2781
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
2782
|
+
[transportSymbol] = true;
|
|
2783
|
+
[Symbol.toStringTag] = "@libp2p/websockets";
|
|
2784
|
+
[serviceCapabilities] = [
|
|
2785
|
+
"@libp2p/transport"
|
|
2786
|
+
];
|
|
2787
|
+
async dial(ma, options) {
|
|
2788
|
+
this.log("dialing %s", ma);
|
|
2789
|
+
options = options ?? {};
|
|
2790
|
+
const maConn = webSocketToMaConn({
|
|
2791
|
+
websocket: await this._connect(ma, options),
|
|
2792
|
+
remoteAddr: ma,
|
|
2793
|
+
metrics: this.metrics?.dialerEvents,
|
|
2794
|
+
direction: "outbound",
|
|
2795
|
+
log: this.components.logger.forComponent("libp2p:websockets:connection"),
|
|
2796
|
+
maxBufferedAmount: this.init.maxBufferedAmount,
|
|
2797
|
+
bufferedAmountPollInterval: this.init.bufferedAmountPollInterval
|
|
2798
|
+
});
|
|
2799
|
+
this.log("new outbound connection %s", maConn.remoteAddr);
|
|
2800
|
+
const conn = await options.upgrader.upgradeOutbound(maConn, options);
|
|
2801
|
+
this.log("outbound connection %s upgraded", maConn.remoteAddr);
|
|
2802
|
+
return conn;
|
|
2803
|
+
}
|
|
2804
|
+
async _connect(ma, options) {
|
|
2805
|
+
options?.signal?.throwIfAborted();
|
|
2806
|
+
const uri = multiaddrToUri(ma);
|
|
2807
|
+
this.log("create websocket connection to %s", uri);
|
|
2808
|
+
const websocket = new WebSocket(uri);
|
|
2809
|
+
websocket.binaryType = "arraybuffer";
|
|
2810
|
+
try {
|
|
2811
|
+
options.onProgress?.(new CustomProgressEvent("websockets:open-connection"));
|
|
2812
|
+
await pEvent(websocket, "open", options);
|
|
2813
|
+
} catch (err) {
|
|
2814
|
+
if (options.signal?.aborted) {
|
|
2815
|
+
this.metrics?.dialerEvents.increment({ abort: true });
|
|
2816
|
+
throw new ConnectionFailedError(`Could not connect to ${uri}`);
|
|
2817
|
+
} else {
|
|
2818
|
+
this.metrics?.dialerEvents.increment({ error: true });
|
|
2819
|
+
}
|
|
2820
|
+
try {
|
|
2821
|
+
websocket.close();
|
|
2822
|
+
} catch {
|
|
2823
|
+
}
|
|
2824
|
+
throw err;
|
|
150
2825
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
expectedPublicKey
|
|
155
|
-
);
|
|
156
|
-
} catch (error) {
|
|
157
|
-
throw new IdentityError("Failed to verify message", error);
|
|
2826
|
+
this.log("connected %s", ma);
|
|
2827
|
+
this.metrics?.dialerEvents.increment({ connect: true });
|
|
2828
|
+
return websocket;
|
|
158
2829
|
}
|
|
2830
|
+
/**
|
|
2831
|
+
* Creates a WebSockets listener. The provided `handler` function will be called
|
|
2832
|
+
* anytime a new incoming Connection has been successfully upgraded via
|
|
2833
|
+
* `upgrader.upgradeInbound`
|
|
2834
|
+
*/
|
|
2835
|
+
createListener(options) {
|
|
2836
|
+
return createListener({
|
|
2837
|
+
logger: this.logger,
|
|
2838
|
+
events: this.components.events,
|
|
2839
|
+
metrics: this.components.metrics
|
|
2840
|
+
}, {
|
|
2841
|
+
...this.init,
|
|
2842
|
+
...options
|
|
2843
|
+
});
|
|
2844
|
+
}
|
|
2845
|
+
listenFilter(multiaddrs) {
|
|
2846
|
+
return multiaddrs.filter((ma) => WebSockets.exactMatch(ma) || WebSocketsSecure.exactMatch(ma));
|
|
2847
|
+
}
|
|
2848
|
+
dialFilter(multiaddrs) {
|
|
2849
|
+
return this.listenFilter(multiaddrs);
|
|
2850
|
+
}
|
|
2851
|
+
};
|
|
2852
|
+
function webSockets(init = {}) {
|
|
2853
|
+
return (components) => {
|
|
2854
|
+
return new WebSockets2(components, init);
|
|
2855
|
+
};
|
|
159
2856
|
}
|
|
160
2857
|
|
|
161
2858
|
// src/utils/logger.ts
|
|
2859
|
+
init_esm_shims();
|
|
162
2860
|
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
163
2861
|
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
|
|
164
2862
|
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
|
|
@@ -206,7 +2904,8 @@ var logger = createLogger("transport");
|
|
|
206
2904
|
async function createNode(config) {
|
|
207
2905
|
try {
|
|
208
2906
|
const {
|
|
209
|
-
listenAddresses = ["/ip4/0.0.0.0/tcp/0"],
|
|
2907
|
+
listenAddresses = ["/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/tcp/0/ws"],
|
|
2908
|
+
// CVP-0010 §5: Add WebSocket listener
|
|
210
2909
|
bootstrapPeers = [],
|
|
211
2910
|
enableDHT = true,
|
|
212
2911
|
enableRelay = false,
|
|
@@ -222,6 +2921,8 @@ async function createNode(config) {
|
|
|
222
2921
|
...privateKey ? { privateKey } : {},
|
|
223
2922
|
transports: [
|
|
224
2923
|
tcp(),
|
|
2924
|
+
webSockets(),
|
|
2925
|
+
// CVP-0010 §5: WebSocket for firewall traversal
|
|
225
2926
|
circuitRelayTransport()
|
|
226
2927
|
],
|
|
227
2928
|
connectionEncrypters: [noise()],
|
|
@@ -302,7 +3003,11 @@ async function createNode(config) {
|
|
|
302
3003
|
}
|
|
303
3004
|
}
|
|
304
3005
|
|
|
3006
|
+
// src/discovery/agent-card.ts
|
|
3007
|
+
init_esm_shims();
|
|
3008
|
+
|
|
305
3009
|
// src/discovery/agent-card-types.ts
|
|
3010
|
+
init_esm_shims();
|
|
306
3011
|
function isLegacyCard(card) {
|
|
307
3012
|
return Array.isArray(card.capabilities) && card.capabilities.length > 0 && typeof card.capabilities[0] === "string";
|
|
308
3013
|
}
|
|
@@ -432,6 +3137,7 @@ function matchesCapability(card, capability) {
|
|
|
432
3137
|
}
|
|
433
3138
|
|
|
434
3139
|
// src/discovery/agent-card-schema.ts
|
|
3140
|
+
init_esm_shims();
|
|
435
3141
|
var CLAWIVERSE_CONTEXT = "https://clawiverse.org/context/v1";
|
|
436
3142
|
var SCHEMA_ORG_CONTEXT = "https://schema.org";
|
|
437
3143
|
var clawiverseContext = {
|
|
@@ -490,6 +3196,9 @@ function isValidContext(context) {
|
|
|
490
3196
|
if (!Array.isArray(context)) return false;
|
|
491
3197
|
return context.every((c) => typeof c === "string");
|
|
492
3198
|
}
|
|
3199
|
+
|
|
3200
|
+
// src/discovery/agent-card-encoder.ts
|
|
3201
|
+
init_esm_shims();
|
|
493
3202
|
function encodeForDHT(card) {
|
|
494
3203
|
try {
|
|
495
3204
|
const { "@context": _, ...cardWithoutContext } = card;
|
|
@@ -557,6 +3266,15 @@ function getEncodedSize(card) {
|
|
|
557
3266
|
json: encodeForWeb(card).length
|
|
558
3267
|
};
|
|
559
3268
|
}
|
|
3269
|
+
|
|
3270
|
+
// src/discovery/dht.ts
|
|
3271
|
+
init_esm_shims();
|
|
3272
|
+
|
|
3273
|
+
// src/discovery/semantic-search.ts
|
|
3274
|
+
init_esm_shims();
|
|
3275
|
+
|
|
3276
|
+
// src/discovery/search-index.ts
|
|
3277
|
+
init_esm_shims();
|
|
560
3278
|
var logger2 = createLogger("search-index");
|
|
561
3279
|
var SearchIndex = class {
|
|
562
3280
|
cards = /* @__PURE__ */ new Map();
|
|
@@ -718,6 +3436,7 @@ var SearchIndex = class {
|
|
|
718
3436
|
};
|
|
719
3437
|
|
|
720
3438
|
// src/discovery/capability-matcher.ts
|
|
3439
|
+
init_esm_shims();
|
|
721
3440
|
var CapabilityMatcher = class {
|
|
722
3441
|
/**
|
|
723
3442
|
* Match a query against a capability
|
|
@@ -1056,10 +3775,10 @@ async function readDIDList(dht, key) {
|
|
|
1056
3775
|
return [];
|
|
1057
3776
|
}
|
|
1058
3777
|
async function writeDIDList(dht, key, dids) {
|
|
1059
|
-
const
|
|
3778
|
+
const value2 = fromString([...new Set(dids)].join("\n"));
|
|
1060
3779
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
1061
3780
|
try {
|
|
1062
|
-
for await (const _ of dht.put(key,
|
|
3781
|
+
for await (const _ of dht.put(key, value2, { signal: AbortSignal.timeout(3e4) })) {
|
|
1063
3782
|
}
|
|
1064
3783
|
return;
|
|
1065
3784
|
} catch (e) {
|
|
@@ -1261,6 +3980,7 @@ function createDHTOperations(libp2p) {
|
|
|
1261
3980
|
}
|
|
1262
3981
|
|
|
1263
3982
|
// src/messaging/envelope.ts
|
|
3983
|
+
init_esm_shims();
|
|
1264
3984
|
function createEnvelope(from, to, type, protocol, payload, replyTo) {
|
|
1265
3985
|
return {
|
|
1266
3986
|
id: generateMessageId(),
|
|
@@ -1307,6 +4027,9 @@ function validateEnvelope(msg) {
|
|
|
1307
4027
|
function generateMessageId() {
|
|
1308
4028
|
return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
|
|
1309
4029
|
}
|
|
4030
|
+
|
|
4031
|
+
// src/messaging/codec.ts
|
|
4032
|
+
init_esm_shims();
|
|
1310
4033
|
function encodeMessage(envelope) {
|
|
1311
4034
|
try {
|
|
1312
4035
|
return encode(envelope);
|
|
@@ -1335,6 +4058,9 @@ function decodeMessageJSON(json) {
|
|
|
1335
4058
|
throw new MessagingError("Failed to decode message from JSON", error);
|
|
1336
4059
|
}
|
|
1337
4060
|
}
|
|
4061
|
+
|
|
4062
|
+
// src/messaging/router.ts
|
|
4063
|
+
init_esm_shims();
|
|
1338
4064
|
var logger5 = createLogger("router");
|
|
1339
4065
|
function concatUint8Arrays(arrays) {
|
|
1340
4066
|
if (arrays.length === 0) return new Uint8Array(0);
|
|
@@ -1409,14 +4135,25 @@ function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
|
|
|
1409
4135
|
});
|
|
1410
4136
|
const s = await conn.newStream(PROTOCOL_PREFIX, { runOnLimitedConnection: true });
|
|
1411
4137
|
logger5.info("Direct dial succeeded", { addr });
|
|
1412
|
-
return s;
|
|
4138
|
+
return { conn, stream: s };
|
|
1413
4139
|
} catch {
|
|
1414
4140
|
return null;
|
|
1415
4141
|
}
|
|
1416
4142
|
});
|
|
1417
|
-
|
|
1418
|
-
directDialPromises.map((p) => p.then((
|
|
4143
|
+
const winner = await Promise.race(
|
|
4144
|
+
directDialPromises.map((p) => p.then((r) => r || Promise.reject()))
|
|
1419
4145
|
).catch(() => void 0);
|
|
4146
|
+
if (winner) {
|
|
4147
|
+
stream = winner.stream;
|
|
4148
|
+
Promise.allSettled(directDialPromises).then((results) => {
|
|
4149
|
+
for (const result of results) {
|
|
4150
|
+
if (result.status === "fulfilled" && result.value && result.value.stream !== stream) {
|
|
4151
|
+
result.value.conn.close().catch(() => {
|
|
4152
|
+
});
|
|
4153
|
+
}
|
|
4154
|
+
}
|
|
4155
|
+
});
|
|
4156
|
+
}
|
|
1420
4157
|
}
|
|
1421
4158
|
let lastError;
|
|
1422
4159
|
if (!stream) {
|
|
@@ -1434,16 +4171,27 @@ function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
|
|
|
1434
4171
|
logger5.info("Relay connection established", { addr });
|
|
1435
4172
|
const s = await conn.newStream(PROTOCOL_PREFIX, { runOnLimitedConnection: true });
|
|
1436
4173
|
logger5.info("Relay stream opened", { addr });
|
|
1437
|
-
return s;
|
|
4174
|
+
return { conn, stream: s };
|
|
1438
4175
|
} catch (relayErr) {
|
|
1439
4176
|
logger5.warn("Relay dial failed", { addr, error: relayErr.message });
|
|
1440
4177
|
lastError = relayErr;
|
|
1441
4178
|
return null;
|
|
1442
4179
|
}
|
|
1443
4180
|
});
|
|
1444
|
-
|
|
1445
|
-
relayDialPromises.map((p) => p.then((
|
|
4181
|
+
const winner = await Promise.race(
|
|
4182
|
+
relayDialPromises.map((p) => p.then((r) => r || Promise.reject()))
|
|
1446
4183
|
).catch(() => void 0);
|
|
4184
|
+
if (winner) {
|
|
4185
|
+
stream = winner.stream;
|
|
4186
|
+
Promise.allSettled(relayDialPromises).then((results) => {
|
|
4187
|
+
for (const result of results) {
|
|
4188
|
+
if (result.status === "fulfilled" && result.value && result.value.stream !== stream) {
|
|
4189
|
+
result.value.conn.close().catch(() => {
|
|
4190
|
+
});
|
|
4191
|
+
}
|
|
4192
|
+
}
|
|
4193
|
+
});
|
|
4194
|
+
}
|
|
1447
4195
|
}
|
|
1448
4196
|
}
|
|
1449
4197
|
if (!stream && dht && "queryRelayPeers" in dht) {
|
|
@@ -1479,7 +4227,7 @@ function createMessageRouter(libp2p, verifyFn, dht, relayPeers) {
|
|
|
1479
4227
|
if (envelope.type === "request") {
|
|
1480
4228
|
logger5.debug("Waiting for response to request", { id: envelope.id });
|
|
1481
4229
|
try {
|
|
1482
|
-
const RESPONSE_TIMEOUT =
|
|
4230
|
+
const RESPONSE_TIMEOUT = 3e4;
|
|
1483
4231
|
const responsePromise = (async () => {
|
|
1484
4232
|
const responseChunks = [];
|
|
1485
4233
|
for await (const chunk of stream.source) {
|
|
@@ -1545,6 +4293,10 @@ async function handleIncomingStream(stream, handlers, catchAllHandler, verifyFn)
|
|
|
1545
4293
|
chunks.push(chunk.subarray());
|
|
1546
4294
|
}
|
|
1547
4295
|
const data = concatUint8Arrays(chunks);
|
|
4296
|
+
if (data.length === 0) {
|
|
4297
|
+
logger5.debug("Received empty stream, ignoring");
|
|
4298
|
+
return;
|
|
4299
|
+
}
|
|
1548
4300
|
const envelope = decodeMessage(data);
|
|
1549
4301
|
if (!validateEnvelope(envelope)) {
|
|
1550
4302
|
logger5.warn("Received invalid message envelope");
|
|
@@ -1616,7 +4368,593 @@ async function handleIncomingStream(stream, handlers, catchAllHandler, verifyFn)
|
|
|
1616
4368
|
}
|
|
1617
4369
|
}
|
|
1618
4370
|
|
|
4371
|
+
// src/messaging/types.ts
|
|
4372
|
+
init_esm_shims();
|
|
4373
|
+
|
|
4374
|
+
// src/messaging/storage.ts
|
|
4375
|
+
init_esm_shims();
|
|
4376
|
+
var logger6 = createLogger("message-storage");
|
|
4377
|
+
var MessageStorage = class {
|
|
4378
|
+
db;
|
|
4379
|
+
ready = false;
|
|
4380
|
+
constructor(dbPath) {
|
|
4381
|
+
this.db = new Level(dbPath, { valueEncoding: "json" });
|
|
4382
|
+
}
|
|
4383
|
+
async open() {
|
|
4384
|
+
await this.db.open();
|
|
4385
|
+
this.ready = true;
|
|
4386
|
+
logger6.info("Message storage opened");
|
|
4387
|
+
}
|
|
4388
|
+
async close() {
|
|
4389
|
+
if (this.ready) {
|
|
4390
|
+
await this.db.close();
|
|
4391
|
+
this.ready = false;
|
|
4392
|
+
logger6.info("Message storage closed");
|
|
4393
|
+
}
|
|
4394
|
+
}
|
|
4395
|
+
// ─── Message Operations ───────────────────────────────────────────────────
|
|
4396
|
+
async putMessage(msg) {
|
|
4397
|
+
const ts = String(msg.receivedAt ?? msg.sentAt ?? Date.now()).padStart(16, "0");
|
|
4398
|
+
const key = `msg:${msg.direction}:${ts}:${msg.envelope.id}`;
|
|
4399
|
+
await this.db.put(key, msg);
|
|
4400
|
+
const idxKey = `idx:from:${msg.envelope.from}:${ts}:${msg.envelope.id}`;
|
|
4401
|
+
await this.db.put(idxKey, "1");
|
|
4402
|
+
}
|
|
4403
|
+
async getMessage(id) {
|
|
4404
|
+
for (const direction of ["inbound", "outbound"]) {
|
|
4405
|
+
const prefix = `msg:${direction}:`;
|
|
4406
|
+
for await (const [, value2] of this.db.iterator({
|
|
4407
|
+
gte: prefix,
|
|
4408
|
+
lte: prefix + "\xFF",
|
|
4409
|
+
valueEncoding: "json"
|
|
4410
|
+
})) {
|
|
4411
|
+
if (value2.envelope.id === id) return value2;
|
|
4412
|
+
}
|
|
4413
|
+
}
|
|
4414
|
+
return null;
|
|
4415
|
+
}
|
|
4416
|
+
async updateMessage(id, updates) {
|
|
4417
|
+
const msg = await this.getMessage(id);
|
|
4418
|
+
if (!msg) return;
|
|
4419
|
+
const ts = String(msg.receivedAt ?? msg.sentAt ?? Date.now()).padStart(16, "0");
|
|
4420
|
+
const key = `msg:${msg.direction}:${ts}:${id}`;
|
|
4421
|
+
await this.db.put(key, { ...msg, ...updates });
|
|
4422
|
+
}
|
|
4423
|
+
async deleteMessage(id) {
|
|
4424
|
+
const msg = await this.getMessage(id);
|
|
4425
|
+
if (!msg) return;
|
|
4426
|
+
const ts = String(msg.receivedAt ?? msg.sentAt ?? Date.now()).padStart(16, "0");
|
|
4427
|
+
const key = `msg:${msg.direction}:${ts}:${id}`;
|
|
4428
|
+
const idxKey = `idx:from:${msg.envelope.from}:${ts}:${id}`;
|
|
4429
|
+
await this.db.batch([
|
|
4430
|
+
{ type: "del", key },
|
|
4431
|
+
{ type: "del", key: idxKey }
|
|
4432
|
+
]);
|
|
4433
|
+
}
|
|
4434
|
+
async queryMessages(direction, filter = {}, pagination = {}) {
|
|
4435
|
+
const { limit = 50, offset = 0 } = pagination;
|
|
4436
|
+
const prefix = `msg:${direction}:`;
|
|
4437
|
+
const results = [];
|
|
4438
|
+
let total = 0;
|
|
4439
|
+
let skipped = 0;
|
|
4440
|
+
for await (const [, value2] of this.db.iterator({
|
|
4441
|
+
gte: prefix,
|
|
4442
|
+
lte: prefix + "\xFF",
|
|
4443
|
+
reverse: true,
|
|
4444
|
+
// newest first
|
|
4445
|
+
valueEncoding: "json"
|
|
4446
|
+
})) {
|
|
4447
|
+
if (!this.matchesFilter(value2, filter)) continue;
|
|
4448
|
+
total++;
|
|
4449
|
+
if (skipped < offset) {
|
|
4450
|
+
skipped++;
|
|
4451
|
+
continue;
|
|
4452
|
+
}
|
|
4453
|
+
if (results.length < limit) results.push(value2);
|
|
4454
|
+
}
|
|
4455
|
+
return {
|
|
4456
|
+
messages: results,
|
|
4457
|
+
total,
|
|
4458
|
+
hasMore: total > offset + results.length
|
|
4459
|
+
};
|
|
4460
|
+
}
|
|
4461
|
+
matchesFilter(msg, filter) {
|
|
4462
|
+
if (filter.fromDid) {
|
|
4463
|
+
const froms = Array.isArray(filter.fromDid) ? filter.fromDid : [filter.fromDid];
|
|
4464
|
+
if (!froms.includes(msg.envelope.from)) return false;
|
|
4465
|
+
}
|
|
4466
|
+
if (filter.toDid) {
|
|
4467
|
+
const tos = Array.isArray(filter.toDid) ? filter.toDid : [filter.toDid];
|
|
4468
|
+
if (!tos.includes(msg.envelope.to)) return false;
|
|
4469
|
+
}
|
|
4470
|
+
if (filter.protocol) {
|
|
4471
|
+
const protos = Array.isArray(filter.protocol) ? filter.protocol : [filter.protocol];
|
|
4472
|
+
if (!protos.includes(msg.envelope.protocol)) return false;
|
|
4473
|
+
}
|
|
4474
|
+
if (filter.type && msg.envelope.type !== filter.type) return false;
|
|
4475
|
+
if (filter.unreadOnly && msg.readAt != null) return false;
|
|
4476
|
+
if (filter.status) {
|
|
4477
|
+
const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
|
|
4478
|
+
if (!statuses.includes(msg.status)) return false;
|
|
4479
|
+
}
|
|
4480
|
+
if (filter.maxAge) {
|
|
4481
|
+
const age = Date.now() - (msg.receivedAt ?? msg.sentAt ?? 0);
|
|
4482
|
+
if (age > filter.maxAge) return false;
|
|
4483
|
+
}
|
|
4484
|
+
if (filter.minTrustScore != null && (msg.trustScore ?? 0) < filter.minTrustScore) return false;
|
|
4485
|
+
return true;
|
|
4486
|
+
}
|
|
4487
|
+
async countMessages(direction, filter = {}) {
|
|
4488
|
+
const prefix = `msg:${direction}:`;
|
|
4489
|
+
let count = 0;
|
|
4490
|
+
for await (const [, value2] of this.db.iterator({
|
|
4491
|
+
gte: prefix,
|
|
4492
|
+
lte: prefix + "\xFF",
|
|
4493
|
+
valueEncoding: "json"
|
|
4494
|
+
})) {
|
|
4495
|
+
if (this.matchesFilter(value2, filter)) count++;
|
|
4496
|
+
}
|
|
4497
|
+
return count;
|
|
4498
|
+
}
|
|
4499
|
+
// ─── Blocklist ────────────────────────────────────────────────────────────
|
|
4500
|
+
async putBlock(entry) {
|
|
4501
|
+
await this.db.put(`block:${entry.did}`, entry);
|
|
4502
|
+
}
|
|
4503
|
+
async getBlock(did) {
|
|
4504
|
+
try {
|
|
4505
|
+
return await this.db.get(`block:${did}`);
|
|
4506
|
+
} catch {
|
|
4507
|
+
return null;
|
|
4508
|
+
}
|
|
4509
|
+
}
|
|
4510
|
+
async deleteBlock(did) {
|
|
4511
|
+
try {
|
|
4512
|
+
await this.db.del(`block:${did}`);
|
|
4513
|
+
} catch {
|
|
4514
|
+
}
|
|
4515
|
+
}
|
|
4516
|
+
async listBlocked() {
|
|
4517
|
+
const results = [];
|
|
4518
|
+
for await (const [, value2] of this.db.iterator({
|
|
4519
|
+
gte: "block:",
|
|
4520
|
+
lte: "block:\xFF",
|
|
4521
|
+
valueEncoding: "json"
|
|
4522
|
+
})) {
|
|
4523
|
+
results.push(value2);
|
|
4524
|
+
}
|
|
4525
|
+
return results;
|
|
4526
|
+
}
|
|
4527
|
+
// ─── Allowlist ────────────────────────────────────────────────────────────
|
|
4528
|
+
async putAllow(entry) {
|
|
4529
|
+
await this.db.put(`allow:${entry.did}`, entry);
|
|
4530
|
+
}
|
|
4531
|
+
async getAllow(did) {
|
|
4532
|
+
try {
|
|
4533
|
+
return await this.db.get(`allow:${did}`);
|
|
4534
|
+
} catch {
|
|
4535
|
+
return null;
|
|
4536
|
+
}
|
|
4537
|
+
}
|
|
4538
|
+
async deleteAllow(did) {
|
|
4539
|
+
try {
|
|
4540
|
+
await this.db.del(`allow:${did}`);
|
|
4541
|
+
} catch {
|
|
4542
|
+
}
|
|
4543
|
+
}
|
|
4544
|
+
async listAllowed() {
|
|
4545
|
+
const results = [];
|
|
4546
|
+
for await (const [, value2] of this.db.iterator({
|
|
4547
|
+
gte: "allow:",
|
|
4548
|
+
lte: "allow:\xFF",
|
|
4549
|
+
valueEncoding: "json"
|
|
4550
|
+
})) {
|
|
4551
|
+
results.push(value2);
|
|
4552
|
+
}
|
|
4553
|
+
return results;
|
|
4554
|
+
}
|
|
4555
|
+
// ─── Seen Cache ───────────────────────────────────────────────────────────
|
|
4556
|
+
async putSeen(entry) {
|
|
4557
|
+
await this.db.put(`seen:${entry.messageId}`, entry);
|
|
4558
|
+
}
|
|
4559
|
+
async getSeen(messageId) {
|
|
4560
|
+
try {
|
|
4561
|
+
return await this.db.get(`seen:${messageId}`);
|
|
4562
|
+
} catch {
|
|
4563
|
+
return null;
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
async cleanupSeen(maxAgeMs) {
|
|
4567
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
4568
|
+
const toDelete = [];
|
|
4569
|
+
for await (const [key, value2] of this.db.iterator({
|
|
4570
|
+
gte: "seen:",
|
|
4571
|
+
lte: "seen:\xFF",
|
|
4572
|
+
valueEncoding: "json"
|
|
4573
|
+
})) {
|
|
4574
|
+
if (value2.seenAt < cutoff) toDelete.push(key);
|
|
4575
|
+
}
|
|
4576
|
+
await this.db.batch(toDelete.map((key) => ({ type: "del", key })));
|
|
4577
|
+
}
|
|
4578
|
+
// ─── Rate Limit State ─────────────────────────────────────────────────────
|
|
4579
|
+
async putRateLimit(state) {
|
|
4580
|
+
await this.db.put(`rate:${state.did}`, state);
|
|
4581
|
+
}
|
|
4582
|
+
async getRateLimit(did) {
|
|
4583
|
+
try {
|
|
4584
|
+
return await this.db.get(`rate:${did}`);
|
|
4585
|
+
} catch {
|
|
4586
|
+
return null;
|
|
4587
|
+
}
|
|
4588
|
+
}
|
|
4589
|
+
async cleanupRateLimits(maxAgeMs) {
|
|
4590
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
4591
|
+
const toDelete = [];
|
|
4592
|
+
for await (const [key, value2] of this.db.iterator({
|
|
4593
|
+
gte: "rate:",
|
|
4594
|
+
lte: "rate:\xFF",
|
|
4595
|
+
valueEncoding: "json"
|
|
4596
|
+
})) {
|
|
4597
|
+
if (value2.lastRefill < cutoff) toDelete.push(key);
|
|
4598
|
+
}
|
|
4599
|
+
await this.db.batch(toDelete.map((key) => ({ type: "del", key })));
|
|
4600
|
+
}
|
|
4601
|
+
};
|
|
4602
|
+
|
|
4603
|
+
// src/messaging/queue.ts
|
|
4604
|
+
init_esm_shims();
|
|
4605
|
+
var logger7 = createLogger("message-queue");
|
|
4606
|
+
var MessageQueue = class {
|
|
4607
|
+
storage;
|
|
4608
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
4609
|
+
subCounter = 0;
|
|
4610
|
+
constructor(config) {
|
|
4611
|
+
this.storage = new MessageStorage(config.dbPath);
|
|
4612
|
+
}
|
|
4613
|
+
get store() {
|
|
4614
|
+
return this.storage;
|
|
4615
|
+
}
|
|
4616
|
+
async start() {
|
|
4617
|
+
await this.storage.open();
|
|
4618
|
+
logger7.info("Message queue started");
|
|
4619
|
+
}
|
|
4620
|
+
async stop() {
|
|
4621
|
+
await this.storage.close();
|
|
4622
|
+
this.subscriptions.clear();
|
|
4623
|
+
logger7.info("Message queue stopped");
|
|
4624
|
+
}
|
|
4625
|
+
// ─── Inbox ────────────────────────────────────────────────────────────────
|
|
4626
|
+
async getInbox(filter = {}, pagination = {}) {
|
|
4627
|
+
return this.storage.queryMessages("inbound", filter, pagination);
|
|
4628
|
+
}
|
|
4629
|
+
async getMessage(id) {
|
|
4630
|
+
return this.storage.getMessage(id);
|
|
4631
|
+
}
|
|
4632
|
+
async markAsRead(id) {
|
|
4633
|
+
await this.storage.updateMessage(id, { readAt: Date.now() });
|
|
4634
|
+
}
|
|
4635
|
+
async deleteMessage(id) {
|
|
4636
|
+
await this.storage.deleteMessage(id);
|
|
4637
|
+
}
|
|
4638
|
+
// ─── Outbox ───────────────────────────────────────────────────────────────
|
|
4639
|
+
async getOutbox(pagination = {}) {
|
|
4640
|
+
return this.storage.queryMessages("outbound", {}, pagination);
|
|
4641
|
+
}
|
|
4642
|
+
async retryMessage(id) {
|
|
4643
|
+
await this.storage.updateMessage(id, { status: "pending", error: void 0 });
|
|
4644
|
+
}
|
|
4645
|
+
// ─── Enqueue ──────────────────────────────────────────────────────────────
|
|
4646
|
+
async enqueueInbound(envelope, trustScore) {
|
|
4647
|
+
const msg = {
|
|
4648
|
+
envelope,
|
|
4649
|
+
direction: "inbound",
|
|
4650
|
+
status: "pending",
|
|
4651
|
+
receivedAt: Date.now(),
|
|
4652
|
+
trustScore
|
|
4653
|
+
};
|
|
4654
|
+
await this.storage.putMessage(msg);
|
|
4655
|
+
logger7.debug("Enqueued inbound message", { id: envelope.id, from: envelope.from });
|
|
4656
|
+
this.notifySubscribers(msg);
|
|
4657
|
+
return msg;
|
|
4658
|
+
}
|
|
4659
|
+
async enqueueOutbound(envelope) {
|
|
4660
|
+
const msg = {
|
|
4661
|
+
envelope,
|
|
4662
|
+
direction: "outbound",
|
|
4663
|
+
status: "pending",
|
|
4664
|
+
sentAt: Date.now()
|
|
4665
|
+
};
|
|
4666
|
+
await this.storage.putMessage(msg);
|
|
4667
|
+
logger7.debug("Enqueued outbound message", { id: envelope.id, to: envelope.to });
|
|
4668
|
+
return msg;
|
|
4669
|
+
}
|
|
4670
|
+
async markOutboundDelivered(id) {
|
|
4671
|
+
await this.storage.updateMessage(id, { status: "delivered" });
|
|
4672
|
+
}
|
|
4673
|
+
async markOutboundFailed(id, error) {
|
|
4674
|
+
await this.storage.updateMessage(id, { status: "failed", error });
|
|
4675
|
+
}
|
|
4676
|
+
// ─── Subscriptions ────────────────────────────────────────────────────────
|
|
4677
|
+
subscribe(filter, callback) {
|
|
4678
|
+
const id = `sub_${++this.subCounter}`;
|
|
4679
|
+
this.subscriptions.set(id, { id, filter, callback });
|
|
4680
|
+
logger7.debug("Subscription added", { id });
|
|
4681
|
+
return id;
|
|
4682
|
+
}
|
|
4683
|
+
unsubscribe(subscriptionId) {
|
|
4684
|
+
this.subscriptions.delete(subscriptionId);
|
|
4685
|
+
logger7.debug("Subscription removed", { id: subscriptionId });
|
|
4686
|
+
}
|
|
4687
|
+
notifySubscribers(msg) {
|
|
4688
|
+
for (const sub of this.subscriptions.values()) {
|
|
4689
|
+
if (this.matchesSubscriptionFilter(msg, sub.filter)) {
|
|
4690
|
+
Promise.resolve(sub.callback(msg)).catch((err) => {
|
|
4691
|
+
logger7.warn("Subscription callback error", { id: sub.id, error: err.message });
|
|
4692
|
+
});
|
|
4693
|
+
}
|
|
4694
|
+
}
|
|
4695
|
+
}
|
|
4696
|
+
matchesSubscriptionFilter(msg, filter) {
|
|
4697
|
+
if (filter.fromDid) {
|
|
4698
|
+
const froms = Array.isArray(filter.fromDid) ? filter.fromDid : [filter.fromDid];
|
|
4699
|
+
if (!froms.includes(msg.envelope.from)) return false;
|
|
4700
|
+
}
|
|
4701
|
+
if (filter.protocol) {
|
|
4702
|
+
const protos = Array.isArray(filter.protocol) ? filter.protocol : [filter.protocol];
|
|
4703
|
+
if (!protos.includes(msg.envelope.protocol)) return false;
|
|
4704
|
+
}
|
|
4705
|
+
if (filter.type && msg.envelope.type !== filter.type) return false;
|
|
4706
|
+
return true;
|
|
4707
|
+
}
|
|
4708
|
+
// ─── Stats ────────────────────────────────────────────────────────────────
|
|
4709
|
+
async getStats() {
|
|
4710
|
+
const [inboxTotal, inboxUnread, outboxPending, outboxFailed, blocked, allowed] = await Promise.all([
|
|
4711
|
+
this.storage.countMessages("inbound"),
|
|
4712
|
+
this.storage.countMessages("inbound", { unreadOnly: true }),
|
|
4713
|
+
this.storage.countMessages("outbound", { status: "pending" }),
|
|
4714
|
+
this.storage.countMessages("outbound", { status: "failed" }),
|
|
4715
|
+
this.storage.listBlocked().then((l) => l.length),
|
|
4716
|
+
this.storage.listAllowed().then((l) => l.length)
|
|
4717
|
+
]);
|
|
4718
|
+
return {
|
|
4719
|
+
inboxTotal,
|
|
4720
|
+
inboxUnread,
|
|
4721
|
+
outboxPending,
|
|
4722
|
+
outboxFailed,
|
|
4723
|
+
blockedAgents: blocked,
|
|
4724
|
+
allowedAgents: allowed,
|
|
4725
|
+
rateLimitedAgents: 0
|
|
4726
|
+
};
|
|
4727
|
+
}
|
|
4728
|
+
};
|
|
4729
|
+
|
|
4730
|
+
// src/messaging/defense.ts
|
|
4731
|
+
init_esm_shims();
|
|
4732
|
+
|
|
4733
|
+
// src/messaging/rate-limiter.ts
|
|
4734
|
+
init_esm_shims();
|
|
4735
|
+
var TokenBucket = class {
|
|
4736
|
+
tokens;
|
|
4737
|
+
lastRefill;
|
|
4738
|
+
capacity;
|
|
4739
|
+
refillRate;
|
|
4740
|
+
// tokens per ms
|
|
4741
|
+
constructor(config, initialTokens, lastRefill) {
|
|
4742
|
+
this.capacity = config.capacity;
|
|
4743
|
+
this.refillRate = config.refillRate;
|
|
4744
|
+
this.tokens = initialTokens ?? config.capacity;
|
|
4745
|
+
this.lastRefill = lastRefill ?? Date.now();
|
|
4746
|
+
}
|
|
4747
|
+
/** Attempt to consume one token. Returns true if allowed. */
|
|
4748
|
+
consume() {
|
|
4749
|
+
this.refill();
|
|
4750
|
+
if (this.tokens >= 1) {
|
|
4751
|
+
this.tokens -= 1;
|
|
4752
|
+
return true;
|
|
4753
|
+
}
|
|
4754
|
+
return false;
|
|
4755
|
+
}
|
|
4756
|
+
getRemaining() {
|
|
4757
|
+
this.refill();
|
|
4758
|
+
return Math.floor(this.tokens);
|
|
4759
|
+
}
|
|
4760
|
+
/** Milliseconds until at least one token is available */
|
|
4761
|
+
getResetTime() {
|
|
4762
|
+
this.refill();
|
|
4763
|
+
if (this.tokens >= 1) return 0;
|
|
4764
|
+
const needed = 1 - this.tokens;
|
|
4765
|
+
return Math.ceil(needed / this.refillRate);
|
|
4766
|
+
}
|
|
4767
|
+
/** Serialize state for persistence */
|
|
4768
|
+
toState() {
|
|
4769
|
+
return { tokens: this.tokens, lastRefill: this.lastRefill };
|
|
4770
|
+
}
|
|
4771
|
+
refill() {
|
|
4772
|
+
const now = Date.now();
|
|
4773
|
+
const elapsed = now - this.lastRefill;
|
|
4774
|
+
const newTokens = elapsed * this.refillRate;
|
|
4775
|
+
this.tokens = Math.min(this.capacity, this.tokens + newTokens);
|
|
4776
|
+
this.lastRefill = now;
|
|
4777
|
+
}
|
|
4778
|
+
};
|
|
4779
|
+
var DEFAULT_RATE_LIMIT_TIERS = {
|
|
4780
|
+
newAgent: { capacity: 10, refillRate: 10 / (60 * 1e3) },
|
|
4781
|
+
// 10/min, burst 10
|
|
4782
|
+
established: { capacity: 100, refillRate: 60 / (60 * 1e3) },
|
|
4783
|
+
// 60/min, burst 100
|
|
4784
|
+
trusted: { capacity: 1e3, refillRate: 600 / (60 * 1e3) }
|
|
4785
|
+
// 600/min, burst 1000
|
|
4786
|
+
};
|
|
4787
|
+
function getTierConfig(trustScore, tiers) {
|
|
4788
|
+
if (trustScore >= 0.6) return tiers.trusted;
|
|
4789
|
+
if (trustScore >= 0.3) return tiers.established;
|
|
4790
|
+
return tiers.newAgent;
|
|
4791
|
+
}
|
|
4792
|
+
|
|
4793
|
+
// src/messaging/defense.ts
|
|
4794
|
+
var logger8 = createLogger("defense");
|
|
4795
|
+
var DefenseMiddleware = class {
|
|
4796
|
+
trust;
|
|
4797
|
+
storage;
|
|
4798
|
+
minTrustScore;
|
|
4799
|
+
autoBlockThreshold;
|
|
4800
|
+
tiers;
|
|
4801
|
+
seenTtlMs;
|
|
4802
|
+
// In-memory LRU-style seen cache (backed by LevelDB for persistence)
|
|
4803
|
+
seenCache = /* @__PURE__ */ new Map();
|
|
4804
|
+
// id → seenAt
|
|
4805
|
+
MAX_SEEN_CACHE = 1e4;
|
|
4806
|
+
// In-memory token buckets (backed by LevelDB for persistence)
|
|
4807
|
+
buckets = /* @__PURE__ */ new Map();
|
|
4808
|
+
constructor(config) {
|
|
4809
|
+
this.trust = config.trustSystem;
|
|
4810
|
+
this.storage = config.storage;
|
|
4811
|
+
this.minTrustScore = config.minTrustScore ?? 0;
|
|
4812
|
+
this.autoBlockThreshold = config.autoBlockThreshold ?? 0.1;
|
|
4813
|
+
this.tiers = config.rateLimitTiers ?? DEFAULT_RATE_LIMIT_TIERS;
|
|
4814
|
+
this.seenTtlMs = config.seenTtlMs ?? 60 * 60 * 1e3;
|
|
4815
|
+
}
|
|
4816
|
+
/**
|
|
4817
|
+
* Run all defense checks on an incoming message.
|
|
4818
|
+
* Returns { allowed: true } if the message should be processed,
|
|
4819
|
+
* or { allowed: false, reason } if it should be dropped.
|
|
4820
|
+
*/
|
|
4821
|
+
async checkMessage(envelope) {
|
|
4822
|
+
const did = envelope.from;
|
|
4823
|
+
if (await this.isAllowed(did)) {
|
|
4824
|
+
this.markAsSeen(envelope.id);
|
|
4825
|
+
return { allowed: true };
|
|
4826
|
+
}
|
|
4827
|
+
if (await this.isBlocked(did)) {
|
|
4828
|
+
logger8.debug("Message rejected: blocked", { id: envelope.id, from: did });
|
|
4829
|
+
return { allowed: false, reason: "blocked" };
|
|
4830
|
+
}
|
|
4831
|
+
if (this.hasSeen(envelope.id)) {
|
|
4832
|
+
logger8.debug("Message rejected: duplicate", { id: envelope.id });
|
|
4833
|
+
return { allowed: false, reason: "duplicate" };
|
|
4834
|
+
}
|
|
4835
|
+
let trustScore = 0;
|
|
4836
|
+
try {
|
|
4837
|
+
const score = await this.trust.getTrustScore(did);
|
|
4838
|
+
trustScore = score.interactionScore;
|
|
4839
|
+
if (trustScore < this.autoBlockThreshold && trustScore > 0) {
|
|
4840
|
+
logger8.warn("Auto-blocking low-trust agent", { did, trustScore });
|
|
4841
|
+
await this.blockAgent(did, `Auto-blocked: trust score ${trustScore.toFixed(2)} below threshold`);
|
|
4842
|
+
return { allowed: false, reason: "blocked" };
|
|
4843
|
+
}
|
|
4844
|
+
if (trustScore < this.minTrustScore) {
|
|
4845
|
+
logger8.debug("Message rejected: trust too low", { id: envelope.id, trustScore });
|
|
4846
|
+
return { allowed: false, reason: "trust_too_low", trustScore };
|
|
4847
|
+
}
|
|
4848
|
+
} catch (err) {
|
|
4849
|
+
logger8.warn("Trust score lookup failed, using 0", { did, error: err.message });
|
|
4850
|
+
}
|
|
4851
|
+
const rateLimitResult = await this.checkRateLimit(did, trustScore);
|
|
4852
|
+
if (!rateLimitResult.allowed) {
|
|
4853
|
+
logger8.debug("Message rejected: rate limited", {
|
|
4854
|
+
id: envelope.id,
|
|
4855
|
+
from: did,
|
|
4856
|
+
resetTime: rateLimitResult.resetTime
|
|
4857
|
+
});
|
|
4858
|
+
return {
|
|
4859
|
+
allowed: false,
|
|
4860
|
+
reason: "rate_limited",
|
|
4861
|
+
remainingTokens: rateLimitResult.remaining,
|
|
4862
|
+
resetTime: rateLimitResult.resetTime
|
|
4863
|
+
};
|
|
4864
|
+
}
|
|
4865
|
+
this.markAsSeen(envelope.id);
|
|
4866
|
+
return { allowed: true, trustScore, remainingTokens: rateLimitResult.remaining };
|
|
4867
|
+
}
|
|
4868
|
+
// ─── Blocklist ────────────────────────────────────────────────────────────
|
|
4869
|
+
async blockAgent(did, reason, blockedBy = "local") {
|
|
4870
|
+
await this.storage.putBlock({ did, reason, blockedAt: Date.now(), blockedBy });
|
|
4871
|
+
logger8.info("Agent blocked", { did, reason });
|
|
4872
|
+
}
|
|
4873
|
+
async unblockAgent(did) {
|
|
4874
|
+
await this.storage.deleteBlock(did);
|
|
4875
|
+
logger8.info("Agent unblocked", { did });
|
|
4876
|
+
}
|
|
4877
|
+
async isBlocked(did) {
|
|
4878
|
+
return await this.storage.getBlock(did) !== null;
|
|
4879
|
+
}
|
|
4880
|
+
// ─── Allowlist ────────────────────────────────────────────────────────────
|
|
4881
|
+
async allowAgent(did, note) {
|
|
4882
|
+
await this.storage.putAllow({ did, addedAt: Date.now(), note });
|
|
4883
|
+
logger8.info("Agent allowlisted", { did });
|
|
4884
|
+
}
|
|
4885
|
+
async removeFromAllowlist(did) {
|
|
4886
|
+
await this.storage.deleteAllow(did);
|
|
4887
|
+
logger8.info("Agent removed from allowlist", { did });
|
|
4888
|
+
}
|
|
4889
|
+
async isAllowed(did) {
|
|
4890
|
+
return await this.storage.getAllow(did) !== null;
|
|
4891
|
+
}
|
|
4892
|
+
// ─── Rate Limiting ────────────────────────────────────────────────────────
|
|
4893
|
+
async checkRateLimit(did, trustScore) {
|
|
4894
|
+
const tierConfig = getTierConfig(trustScore, this.tiers);
|
|
4895
|
+
let bucket = this.buckets.get(did);
|
|
4896
|
+
if (!bucket) {
|
|
4897
|
+
const persisted = await this.storage.getRateLimit(did);
|
|
4898
|
+
if (persisted) {
|
|
4899
|
+
bucket = new TokenBucket(tierConfig, persisted.tokens, persisted.lastRefill);
|
|
4900
|
+
} else {
|
|
4901
|
+
bucket = new TokenBucket(tierConfig);
|
|
4902
|
+
}
|
|
4903
|
+
this.buckets.set(did, bucket);
|
|
4904
|
+
}
|
|
4905
|
+
const allowed = bucket.consume();
|
|
4906
|
+
const state = bucket.toState();
|
|
4907
|
+
await this.storage.putRateLimit({
|
|
4908
|
+
did,
|
|
4909
|
+
tokens: state.tokens,
|
|
4910
|
+
lastRefill: state.lastRefill,
|
|
4911
|
+
totalRequests: 0,
|
|
4912
|
+
firstSeen: Date.now()
|
|
4913
|
+
});
|
|
4914
|
+
return {
|
|
4915
|
+
allowed,
|
|
4916
|
+
remaining: bucket.getRemaining(),
|
|
4917
|
+
resetTime: bucket.getResetTime(),
|
|
4918
|
+
limit: tierConfig.capacity
|
|
4919
|
+
};
|
|
4920
|
+
}
|
|
4921
|
+
// ─── Seen Cache (deduplication) ───────────────────────────────────────────
|
|
4922
|
+
hasSeen(messageId) {
|
|
4923
|
+
return this.seenCache.has(messageId);
|
|
4924
|
+
}
|
|
4925
|
+
markAsSeen(messageId) {
|
|
4926
|
+
if (this.seenCache.size >= this.MAX_SEEN_CACHE) {
|
|
4927
|
+
const firstKey = this.seenCache.keys().next().value;
|
|
4928
|
+
if (firstKey) this.seenCache.delete(firstKey);
|
|
4929
|
+
}
|
|
4930
|
+
this.seenCache.set(messageId, Date.now());
|
|
4931
|
+
this.storage.putSeen({ messageId, seenAt: Date.now(), fromDid: "" }).catch(() => {
|
|
4932
|
+
});
|
|
4933
|
+
}
|
|
4934
|
+
/** Periodic cleanup of expired seen entries */
|
|
4935
|
+
async cleanupSeen() {
|
|
4936
|
+
const cutoff = Date.now() - this.seenTtlMs;
|
|
4937
|
+
for (const [id, seenAt] of this.seenCache) {
|
|
4938
|
+
if (seenAt < cutoff) this.seenCache.delete(id);
|
|
4939
|
+
}
|
|
4940
|
+
await this.storage.cleanupSeen(this.seenTtlMs);
|
|
4941
|
+
}
|
|
4942
|
+
/** Periodic cleanup of stale rate limit buckets (24h inactive) */
|
|
4943
|
+
async cleanupRateLimits() {
|
|
4944
|
+
const staleMs = 24 * 60 * 60 * 1e3;
|
|
4945
|
+
const cutoff = Date.now() - staleMs;
|
|
4946
|
+
for (const [did, bucket] of this.buckets) {
|
|
4947
|
+
if (bucket.toState().lastRefill < cutoff) this.buckets.delete(did);
|
|
4948
|
+
}
|
|
4949
|
+
await this.storage.cleanupRateLimits(staleMs);
|
|
4950
|
+
}
|
|
4951
|
+
};
|
|
4952
|
+
|
|
4953
|
+
// src/trust/index.ts
|
|
4954
|
+
init_esm_shims();
|
|
4955
|
+
|
|
1619
4956
|
// src/trust/trust-score.ts
|
|
4957
|
+
init_esm_shims();
|
|
1620
4958
|
var TrustMetrics = class {
|
|
1621
4959
|
/**
|
|
1622
4960
|
* Calculate trust score from interaction history
|
|
@@ -1684,7 +5022,10 @@ function createDefaultTrustScore() {
|
|
|
1684
5022
|
lastUpdated: Date.now()
|
|
1685
5023
|
};
|
|
1686
5024
|
}
|
|
1687
|
-
|
|
5025
|
+
|
|
5026
|
+
// src/trust/interaction-history.ts
|
|
5027
|
+
init_esm_shims();
|
|
5028
|
+
var logger9 = createLogger("interaction-history");
|
|
1688
5029
|
var InteractionHistory = class {
|
|
1689
5030
|
db;
|
|
1690
5031
|
constructor(dbPath) {
|
|
@@ -1695,14 +5036,14 @@ var InteractionHistory = class {
|
|
|
1695
5036
|
*/
|
|
1696
5037
|
async open() {
|
|
1697
5038
|
await this.db.open();
|
|
1698
|
-
|
|
5039
|
+
logger9.info("Interaction history database opened", { path: this.db.location });
|
|
1699
5040
|
}
|
|
1700
5041
|
/**
|
|
1701
5042
|
* Close database connection
|
|
1702
5043
|
*/
|
|
1703
5044
|
async close() {
|
|
1704
5045
|
await this.db.close();
|
|
1705
|
-
|
|
5046
|
+
logger9.info("Interaction history database closed");
|
|
1706
5047
|
}
|
|
1707
5048
|
/**
|
|
1708
5049
|
* Record an interaction
|
|
@@ -1710,7 +5051,7 @@ var InteractionHistory = class {
|
|
|
1710
5051
|
async record(interaction) {
|
|
1711
5052
|
const key = `interaction:${interaction.agentDid}:${interaction.timestamp}`;
|
|
1712
5053
|
await this.db.put(key, interaction);
|
|
1713
|
-
|
|
5054
|
+
logger9.debug("Recorded interaction", { agentDid: interaction.agentDid, type: interaction.type });
|
|
1714
5055
|
}
|
|
1715
5056
|
/**
|
|
1716
5057
|
* Get interaction history for an agent
|
|
@@ -1719,17 +5060,17 @@ var InteractionHistory = class {
|
|
|
1719
5060
|
const interactions = [];
|
|
1720
5061
|
const prefix = `interaction:${agentDid}:`;
|
|
1721
5062
|
try {
|
|
1722
|
-
for await (const [_,
|
|
5063
|
+
for await (const [_, value2] of this.db.iterator({
|
|
1723
5064
|
gte: prefix,
|
|
1724
5065
|
lte: prefix + "\xFF",
|
|
1725
5066
|
limit,
|
|
1726
5067
|
reverse: true
|
|
1727
5068
|
// Most recent first
|
|
1728
5069
|
})) {
|
|
1729
|
-
interactions.push(
|
|
5070
|
+
interactions.push(value2);
|
|
1730
5071
|
}
|
|
1731
5072
|
} catch (error) {
|
|
1732
|
-
|
|
5073
|
+
logger9.error("Failed to get interaction history", { agentDid, error });
|
|
1733
5074
|
}
|
|
1734
5075
|
return interactions;
|
|
1735
5076
|
}
|
|
@@ -1768,7 +5109,7 @@ var InteractionHistory = class {
|
|
|
1768
5109
|
}
|
|
1769
5110
|
}
|
|
1770
5111
|
} catch (error) {
|
|
1771
|
-
|
|
5112
|
+
logger9.error("Failed to get all agents", { error });
|
|
1772
5113
|
}
|
|
1773
5114
|
return Array.from(agents);
|
|
1774
5115
|
}
|
|
@@ -1785,7 +5126,7 @@ var InteractionHistory = class {
|
|
|
1785
5126
|
keysToDelete.push(key);
|
|
1786
5127
|
}
|
|
1787
5128
|
await this.db.batch(keysToDelete.map((key) => ({ type: "del", key })));
|
|
1788
|
-
|
|
5129
|
+
logger9.info("Deleted interaction history", { agentDid, count: keysToDelete.length });
|
|
1789
5130
|
}
|
|
1790
5131
|
/**
|
|
1791
5132
|
* Clean up old interactions (older than 90 days)
|
|
@@ -1793,21 +5134,22 @@ var InteractionHistory = class {
|
|
|
1793
5134
|
async cleanup(maxAge = 90 * 24 * 60 * 60 * 1e3) {
|
|
1794
5135
|
const cutoff = Date.now() - maxAge;
|
|
1795
5136
|
const keysToDelete = [];
|
|
1796
|
-
for await (const [key,
|
|
1797
|
-
if (
|
|
5137
|
+
for await (const [key, value2] of this.db.iterator()) {
|
|
5138
|
+
if (value2.timestamp < cutoff) {
|
|
1798
5139
|
keysToDelete.push(key);
|
|
1799
5140
|
}
|
|
1800
5141
|
}
|
|
1801
5142
|
if (keysToDelete.length > 0) {
|
|
1802
5143
|
await this.db.batch(keysToDelete.map((key) => ({ type: "del", key })));
|
|
1803
|
-
|
|
5144
|
+
logger9.info("Cleaned up old interactions", { count: keysToDelete.length });
|
|
1804
5145
|
}
|
|
1805
5146
|
return keysToDelete.length;
|
|
1806
5147
|
}
|
|
1807
5148
|
};
|
|
1808
5149
|
|
|
1809
5150
|
// src/trust/endorsement.ts
|
|
1810
|
-
|
|
5151
|
+
init_esm_shims();
|
|
5152
|
+
var logger10 = createLogger("endorsement");
|
|
1811
5153
|
var EndorsementManager = class {
|
|
1812
5154
|
constructor(db, getPublicKey) {
|
|
1813
5155
|
this.db = db;
|
|
@@ -1834,7 +5176,7 @@ var EndorsementManager = class {
|
|
|
1834
5176
|
...endorsement,
|
|
1835
5177
|
signature
|
|
1836
5178
|
};
|
|
1837
|
-
|
|
5179
|
+
logger10.info("Created endorsement", { from: fromDid, to: toDid, score });
|
|
1838
5180
|
return signedEndorsement;
|
|
1839
5181
|
}
|
|
1840
5182
|
/**
|
|
@@ -1848,7 +5190,7 @@ var EndorsementManager = class {
|
|
|
1848
5190
|
const publicKey = await this.getPublicKey(endorsement.from);
|
|
1849
5191
|
return await verifyFn(signatureBytes, data, publicKey);
|
|
1850
5192
|
} catch (error) {
|
|
1851
|
-
|
|
5193
|
+
logger10.error("Failed to verify endorsement", { error });
|
|
1852
5194
|
return false;
|
|
1853
5195
|
}
|
|
1854
5196
|
}
|
|
@@ -1858,7 +5200,7 @@ var EndorsementManager = class {
|
|
|
1858
5200
|
async publish(endorsement) {
|
|
1859
5201
|
const key = `endorsement:${endorsement.to}:${endorsement.from}`;
|
|
1860
5202
|
await this.db.put(key, endorsement);
|
|
1861
|
-
|
|
5203
|
+
logger10.info("Published endorsement", { from: endorsement.from, to: endorsement.to });
|
|
1862
5204
|
}
|
|
1863
5205
|
/**
|
|
1864
5206
|
* Get all endorsements for an agent
|
|
@@ -1867,14 +5209,14 @@ var EndorsementManager = class {
|
|
|
1867
5209
|
const endorsements = [];
|
|
1868
5210
|
const prefix = `endorsement:${agentDid}:`;
|
|
1869
5211
|
try {
|
|
1870
|
-
for await (const [_,
|
|
5212
|
+
for await (const [_, value2] of this.db.iterator({
|
|
1871
5213
|
gte: prefix,
|
|
1872
5214
|
lte: prefix + "\xFF"
|
|
1873
5215
|
})) {
|
|
1874
|
-
endorsements.push(
|
|
5216
|
+
endorsements.push(value2);
|
|
1875
5217
|
}
|
|
1876
5218
|
} catch (error) {
|
|
1877
|
-
|
|
5219
|
+
logger10.error("Failed to get endorsements", { agentDid, error });
|
|
1878
5220
|
}
|
|
1879
5221
|
return endorsements;
|
|
1880
5222
|
}
|
|
@@ -1884,13 +5226,13 @@ var EndorsementManager = class {
|
|
|
1884
5226
|
async getEndorsementsBy(fromDid) {
|
|
1885
5227
|
const endorsements = [];
|
|
1886
5228
|
try {
|
|
1887
|
-
for await (const [_,
|
|
1888
|
-
if (
|
|
1889
|
-
endorsements.push(
|
|
5229
|
+
for await (const [_, value2] of this.db.iterator()) {
|
|
5230
|
+
if (value2.from === fromDid) {
|
|
5231
|
+
endorsements.push(value2);
|
|
1890
5232
|
}
|
|
1891
5233
|
}
|
|
1892
5234
|
} catch (error) {
|
|
1893
|
-
|
|
5235
|
+
logger10.error("Failed to get endorsements by agent", { fromDid, error });
|
|
1894
5236
|
}
|
|
1895
5237
|
return endorsements;
|
|
1896
5238
|
}
|
|
@@ -1911,10 +5253,13 @@ var EndorsementManager = class {
|
|
|
1911
5253
|
async deleteEndorsement(fromDid, toDid) {
|
|
1912
5254
|
const key = `endorsement:${toDid}:${fromDid}`;
|
|
1913
5255
|
await this.db.del(key);
|
|
1914
|
-
|
|
5256
|
+
logger10.info("Deleted endorsement", { from: fromDid, to: toDid });
|
|
1915
5257
|
}
|
|
1916
5258
|
};
|
|
1917
|
-
|
|
5259
|
+
|
|
5260
|
+
// src/trust/sybil-defense.ts
|
|
5261
|
+
init_esm_shims();
|
|
5262
|
+
var logger11 = createLogger("sybil-defense");
|
|
1918
5263
|
var SybilDefense = class {
|
|
1919
5264
|
rateLimits = /* @__PURE__ */ new Map();
|
|
1920
5265
|
peerFirstSeen = /* @__PURE__ */ new Map();
|
|
@@ -1944,7 +5289,7 @@ var SybilDefense = class {
|
|
|
1944
5289
|
verifyChallenge(solution) {
|
|
1945
5290
|
const { challenge, solution: solutionNonce } = solution;
|
|
1946
5291
|
if (Date.now() - challenge.timestamp > 60 * 60 * 1e3) {
|
|
1947
|
-
|
|
5292
|
+
logger11.warn("Challenge expired", { did: challenge.did });
|
|
1948
5293
|
return false;
|
|
1949
5294
|
}
|
|
1950
5295
|
const data = `${challenge.did}:${challenge.nonce}:${solutionNonce}`;
|
|
@@ -1952,9 +5297,9 @@ var SybilDefense = class {
|
|
|
1952
5297
|
const leadingZeros = this.countLeadingZeroBits(hash);
|
|
1953
5298
|
const valid = leadingZeros >= challenge.difficulty;
|
|
1954
5299
|
if (valid) {
|
|
1955
|
-
|
|
5300
|
+
logger11.info("Challenge verified", { did: challenge.did, leadingZeros });
|
|
1956
5301
|
} else {
|
|
1957
|
-
|
|
5302
|
+
logger11.warn("Challenge failed", { did: challenge.did, leadingZeros, required: challenge.difficulty });
|
|
1958
5303
|
}
|
|
1959
5304
|
return valid;
|
|
1960
5305
|
}
|
|
@@ -1994,7 +5339,7 @@ var SybilDefense = class {
|
|
|
1994
5339
|
record.requests = record.requests.filter(
|
|
1995
5340
|
(t) => now - t < this.RATE_LIMIT_WINDOW
|
|
1996
5341
|
);
|
|
1997
|
-
|
|
5342
|
+
logger11.debug("Recorded request", { did, count: record.requests.length });
|
|
1998
5343
|
}
|
|
1999
5344
|
/**
|
|
2000
5345
|
* Get peer trust level based on age
|
|
@@ -2019,7 +5364,7 @@ var SybilDefense = class {
|
|
|
2019
5364
|
recordPeerSeen(peerId) {
|
|
2020
5365
|
if (!this.peerFirstSeen.has(peerId)) {
|
|
2021
5366
|
this.peerFirstSeen.set(peerId, Date.now());
|
|
2022
|
-
|
|
5367
|
+
logger11.debug("Recorded new peer", { peerId });
|
|
2023
5368
|
}
|
|
2024
5369
|
}
|
|
2025
5370
|
/**
|
|
@@ -2033,7 +5378,7 @@ var SybilDefense = class {
|
|
|
2033
5378
|
this.rateLimits.delete(did);
|
|
2034
5379
|
}
|
|
2035
5380
|
}
|
|
2036
|
-
|
|
5381
|
+
logger11.info("Cleaned up Sybil defense records", {
|
|
2037
5382
|
rateLimits: this.rateLimits.size,
|
|
2038
5383
|
peers: this.peerFirstSeen.size
|
|
2039
5384
|
});
|
|
@@ -2066,7 +5411,7 @@ var SybilDefense = class {
|
|
|
2066
5411
|
return count;
|
|
2067
5412
|
}
|
|
2068
5413
|
};
|
|
2069
|
-
var
|
|
5414
|
+
var logger12 = createLogger("trust-system");
|
|
2070
5415
|
var TrustSystem = class {
|
|
2071
5416
|
metrics;
|
|
2072
5417
|
history;
|
|
@@ -2089,14 +5434,14 @@ var TrustSystem = class {
|
|
|
2089
5434
|
*/
|
|
2090
5435
|
async start() {
|
|
2091
5436
|
await this.history.open();
|
|
2092
|
-
|
|
5437
|
+
logger12.info("Trust system started");
|
|
2093
5438
|
}
|
|
2094
5439
|
/**
|
|
2095
5440
|
* Shutdown the trust system
|
|
2096
5441
|
*/
|
|
2097
5442
|
async stop() {
|
|
2098
5443
|
await this.history.close();
|
|
2099
|
-
|
|
5444
|
+
logger12.info("Trust system stopped");
|
|
2100
5445
|
}
|
|
2101
5446
|
/**
|
|
2102
5447
|
* Record an interaction
|
|
@@ -2185,13 +5530,13 @@ var TrustSystem = class {
|
|
|
2185
5530
|
await this.history.cleanup();
|
|
2186
5531
|
this.sybilDefense.cleanup();
|
|
2187
5532
|
this.trustCache.clear();
|
|
2188
|
-
|
|
5533
|
+
logger12.info("Trust system cleanup completed");
|
|
2189
5534
|
}
|
|
2190
5535
|
};
|
|
2191
5536
|
function createTrustSystem(config) {
|
|
2192
5537
|
return new TrustSystem(config);
|
|
2193
5538
|
}
|
|
2194
5539
|
|
|
2195
|
-
export { CLAWIVERSE_CONTEXT, CapabilityMatcher, CapabilityTypes, ClawiverseError, DiscoveryError, EndorsementManager, IdentityError, InteractionHistory, LogLevel, Logger, MessagingError, ParameterTypes, SCHEMA_ORG_CONTEXT, SearchIndex, SemanticSearchEngine, SybilDefense, TransportError, TrustMetrics, TrustSystem, clawiverseContext, createAgentCard, createDHTOperations, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createNode, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };
|
|
5540
|
+
export { CLAWIVERSE_CONTEXT, CapabilityMatcher, CapabilityTypes, ClawiverseError, DEFAULT_RATE_LIMIT_TIERS, DefenseMiddleware, DiscoveryError, EndorsementManager, IdentityError, InteractionHistory, LogLevel, Logger, MessageQueue, MessageStorage, MessagingError, ParameterTypes, SCHEMA_ORG_CONTEXT, SearchIndex, SemanticSearchEngine, SybilDefense, TokenBucket, TransportError, TrustMetrics, TrustSystem, clawiverseContext, createAgentCard, createDHTOperations, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createNode, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, getTierConfig, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };
|
|
2196
5541
|
//# sourceMappingURL=index.js.map
|
|
2197
5542
|
//# sourceMappingURL=index.js.map
|