shogun-core 3.2.3 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +12 -0
  2. package/dist/browser/shogun-core.js +909 -1804
  3. package/dist/browser/shogun-core.js.map +1 -1
  4. package/dist/{src/gundb → gundb}/db.js +55 -11
  5. package/dist/{src/index.js → index.js} +1 -7
  6. package/dist/{src/managers → managers}/CoreInitializer.js +41 -13
  7. package/dist/{src/storage → storage}/storage.js +22 -9
  8. package/dist/types/{src/gundb → gundb}/db.d.ts +10 -3
  9. package/dist/types/{src/index.d.ts → index.d.ts} +0 -3
  10. package/dist/types/{src/interfaces → interfaces}/shogun.d.ts +2 -0
  11. package/dist/types/{src/storage → storage}/storage.d.ts +2 -1
  12. package/dist/types/{src/types → types}/shogun.d.ts +2 -0
  13. package/package.json +22 -9
  14. package/dist/browser/_e6ae.shogun-core.js +0 -14
  15. package/dist/browser/_e6ae.shogun-core.js.map +0 -1
  16. package/dist/ship/examples/messenger-cli.js +0 -629
  17. package/dist/ship/implementation/SHIP_01.js +0 -650
  18. package/dist/ship/interfaces/ISHIP_01.js +0 -71
  19. package/dist/types/ship/examples/messenger-cli.d.ts +0 -31
  20. package/dist/types/ship/implementation/SHIP_01.d.ts +0 -113
  21. package/dist/types/ship/interfaces/ISHIP_01.d.ts +0 -305
  22. /package/dist/{src/config → config}/simplified-config.js +0 -0
  23. /package/dist/{src/core.js → core.js} +0 -0
  24. /package/dist/{src/examples → examples}/api-test.js +0 -0
  25. /package/dist/{src/examples → examples}/simple-api-test.js +0 -0
  26. /package/dist/{src/gundb → gundb}/api.js +0 -0
  27. /package/dist/{src/gundb → gundb}/crypto.js +0 -0
  28. /package/dist/{src/gundb → gundb}/derive.js +0 -0
  29. /package/dist/{src/gundb → gundb}/errors.js +0 -0
  30. /package/dist/{src/gundb → gundb}/index.js +0 -0
  31. /package/dist/{src/gundb → gundb}/rxjs.js +0 -0
  32. /package/dist/{src/gundb → gundb}/types.js +0 -0
  33. /package/dist/{src/interfaces → interfaces}/common.js +0 -0
  34. /package/dist/{src/interfaces → interfaces}/events.js +0 -0
  35. /package/dist/{src/interfaces → interfaces}/plugin.js +0 -0
  36. /package/dist/{src/interfaces → interfaces}/shogun.js +0 -0
  37. /package/dist/{src/managers → managers}/AuthManager.js +0 -0
  38. /package/dist/{src/managers → managers}/EventManager.js +0 -0
  39. /package/dist/{src/managers → managers}/PluginManager.js +0 -0
  40. /package/dist/{src/migration-test.js → migration-test.js} +0 -0
  41. /package/dist/{src/plugins → plugins}/base.js +0 -0
  42. /package/dist/{src/plugins → plugins}/index.js +0 -0
  43. /package/dist/{src/plugins → plugins}/nostr/index.js +0 -0
  44. /package/dist/{src/plugins → plugins}/nostr/nostrConnector.js +0 -0
  45. /package/dist/{src/plugins → plugins}/nostr/nostrConnectorPlugin.js +0 -0
  46. /package/dist/{src/plugins → plugins}/nostr/nostrSigner.js +0 -0
  47. /package/dist/{src/plugins → plugins}/nostr/types.js +0 -0
  48. /package/dist/{src/plugins → plugins}/oauth/index.js +0 -0
  49. /package/dist/{src/plugins → plugins}/oauth/oauthConnector.js +0 -0
  50. /package/dist/{src/plugins → plugins}/oauth/oauthPlugin.js +0 -0
  51. /package/dist/{src/plugins → plugins}/oauth/types.js +0 -0
  52. /package/dist/{src/plugins → plugins}/web3/index.js +0 -0
  53. /package/dist/{src/plugins → plugins}/web3/types.js +0 -0
  54. /package/dist/{src/plugins → plugins}/web3/web3Connector.js +0 -0
  55. /package/dist/{src/plugins → plugins}/web3/web3ConnectorPlugin.js +0 -0
  56. /package/dist/{src/plugins → plugins}/web3/web3Signer.js +0 -0
  57. /package/dist/{src/plugins → plugins}/webauthn/index.js +0 -0
  58. /package/dist/{src/plugins → plugins}/webauthn/types.js +0 -0
  59. /package/dist/{src/plugins → plugins}/webauthn/webauthn.js +0 -0
  60. /package/dist/{src/plugins → plugins}/webauthn/webauthnPlugin.js +0 -0
  61. /package/dist/{src/plugins → plugins}/webauthn/webauthnSigner.js +0 -0
  62. /package/dist/types/{src/config → config}/simplified-config.d.ts +0 -0
  63. /package/dist/types/{src/core.d.ts → core.d.ts} +0 -0
  64. /package/dist/{src/types → types}/events.js +0 -0
  65. /package/dist/types/{src/examples → examples}/api-test.d.ts +0 -0
  66. /package/dist/types/{src/examples → examples}/simple-api-test.d.ts +0 -0
  67. /package/dist/types/{src/gundb → gundb}/api.d.ts +0 -0
  68. /package/dist/types/{src/gundb → gundb}/crypto.d.ts +0 -0
  69. /package/dist/types/{src/gundb → gundb}/derive.d.ts +0 -0
  70. /package/dist/types/{src/gundb → gundb}/errors.d.ts +0 -0
  71. /package/dist/types/{src/gundb → gundb}/index.d.ts +0 -0
  72. /package/dist/types/{src/gundb → gundb}/rxjs.d.ts +0 -0
  73. /package/dist/types/{src/gundb → gundb}/types.d.ts +0 -0
  74. /package/dist/types/{src/interfaces → interfaces}/common.d.ts +0 -0
  75. /package/dist/types/{src/interfaces → interfaces}/events.d.ts +0 -0
  76. /package/dist/types/{src/interfaces → interfaces}/plugin.d.ts +0 -0
  77. /package/dist/types/{src/managers → managers}/AuthManager.d.ts +0 -0
  78. /package/dist/types/{src/managers → managers}/CoreInitializer.d.ts +0 -0
  79. /package/dist/types/{src/managers → managers}/EventManager.d.ts +0 -0
  80. /package/dist/types/{src/managers → managers}/PluginManager.d.ts +0 -0
  81. /package/dist/types/{src/migration-test.d.ts → migration-test.d.ts} +0 -0
  82. /package/dist/types/{src/plugins → plugins}/base.d.ts +0 -0
  83. /package/dist/types/{src/plugins → plugins}/index.d.ts +0 -0
  84. /package/dist/types/{src/plugins → plugins}/nostr/index.d.ts +0 -0
  85. /package/dist/types/{src/plugins → plugins}/nostr/nostrConnector.d.ts +0 -0
  86. /package/dist/types/{src/plugins → plugins}/nostr/nostrConnectorPlugin.d.ts +0 -0
  87. /package/dist/types/{src/plugins → plugins}/nostr/nostrSigner.d.ts +0 -0
  88. /package/dist/types/{src/plugins → plugins}/nostr/types.d.ts +0 -0
  89. /package/dist/types/{src/plugins → plugins}/oauth/index.d.ts +0 -0
  90. /package/dist/types/{src/plugins → plugins}/oauth/oauthConnector.d.ts +0 -0
  91. /package/dist/types/{src/plugins → plugins}/oauth/oauthPlugin.d.ts +0 -0
  92. /package/dist/types/{src/plugins → plugins}/oauth/types.d.ts +0 -0
  93. /package/dist/types/{src/plugins → plugins}/web3/index.d.ts +0 -0
  94. /package/dist/types/{src/plugins → plugins}/web3/types.d.ts +0 -0
  95. /package/dist/types/{src/plugins → plugins}/web3/web3Connector.d.ts +0 -0
  96. /package/dist/types/{src/plugins → plugins}/web3/web3ConnectorPlugin.d.ts +0 -0
  97. /package/dist/types/{src/plugins → plugins}/web3/web3Signer.d.ts +0 -0
  98. /package/dist/types/{src/plugins → plugins}/webauthn/index.d.ts +0 -0
  99. /package/dist/types/{src/plugins → plugins}/webauthn/types.d.ts +0 -0
  100. /package/dist/types/{src/plugins → plugins}/webauthn/webauthn.d.ts +0 -0
  101. /package/dist/types/{src/plugins → plugins}/webauthn/webauthnPlugin.d.ts +0 -0
  102. /package/dist/types/{src/plugins → plugins}/webauthn/webauthnSigner.d.ts +0 -0
  103. /package/dist/{src/types → types}/shogun.js +0 -0
  104. /package/dist/types/{src/types → types}/events.d.ts +0 -0
  105. /package/dist/types/{src/utils → utils}/errorHandler.d.ts +0 -0
  106. /package/dist/types/{src/utils → utils}/eventEmitter.d.ts +0 -0
  107. /package/dist/types/{src/utils → utils}/validation.d.ts +0 -0
  108. /package/dist/{src/utils → utils}/errorHandler.js +0 -0
  109. /package/dist/{src/utils → utils}/eventEmitter.js +0 -0
  110. /package/dist/{src/utils → utils}/validation.js +0 -0
@@ -7999,14 +7999,7 @@ function output(out, instance) {
7999
7999
  }
8000
8000
  }
8001
8001
  exports.output = output;
8002
- const assert = {
8003
- number,
8004
- bool,
8005
- bytes,
8006
- hash,
8007
- exists,
8008
- output,
8009
- };
8002
+ const assert = { number, bool, bytes, hash, exists, output };
8010
8003
  exports["default"] = assert;
8011
8004
  //# sourceMappingURL=_assert.js.map
8012
8005
 
@@ -8053,7 +8046,7 @@ class SHA2 extends utils_js_1.Hash {
8053
8046
  this.view = (0, utils_js_1.createView)(this.buffer);
8054
8047
  }
8055
8048
  update(data) {
8056
- _assert_js_1.default.exists(this);
8049
+ (0, _assert_js_1.exists)(this);
8057
8050
  const { view, buffer, blockLen } = this;
8058
8051
  data = (0, utils_js_1.toBytes)(data);
8059
8052
  const len = data.length;
@@ -8079,8 +8072,8 @@ class SHA2 extends utils_js_1.Hash {
8079
8072
  return this;
8080
8073
  }
8081
8074
  digestInto(out) {
8082
- _assert_js_1.default.exists(this);
8083
- _assert_js_1.default.output(out, this);
8075
+ (0, _assert_js_1.exists)(this);
8076
+ (0, _assert_js_1.output)(out, this);
8084
8077
  this.finished = true;
8085
8078
  // Padding
8086
8079
  // We can avoid allocation of buffer for padding completely if it
@@ -8149,9 +8142,9 @@ exports.SHA2 = SHA2;
8149
8142
  "use strict";
8150
8143
 
8151
8144
  Object.defineProperty(exports, "__esModule", ({ value: true }));
8152
- exports.add = exports.toBig = exports.split = exports.fromBig = void 0;
8153
- const U32_MASK64 = BigInt(2 ** 32 - 1);
8154
- const _32n = BigInt(32);
8145
+ exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.add = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = exports.split = exports.fromBig = void 0;
8146
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
8147
+ const _32n = /* @__PURE__ */ BigInt(32);
8155
8148
  // We are not using BigUint64Array, because they are extremely slow as per 2022
8156
8149
  function fromBig(n, le = false) {
8157
8150
  if (le)
@@ -8172,26 +8165,37 @@ exports.split = split;
8172
8165
  const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
8173
8166
  exports.toBig = toBig;
8174
8167
  // for Shift in [0, 32)
8175
- const shrSH = (h, l, s) => h >>> s;
8168
+ const shrSH = (h, _l, s) => h >>> s;
8169
+ exports.shrSH = shrSH;
8176
8170
  const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
8171
+ exports.shrSL = shrSL;
8177
8172
  // Right rotate for Shift in [1, 32)
8178
8173
  const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
8174
+ exports.rotrSH = rotrSH;
8179
8175
  const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
8176
+ exports.rotrSL = rotrSL;
8180
8177
  // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
8181
8178
  const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
8179
+ exports.rotrBH = rotrBH;
8182
8180
  const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
8181
+ exports.rotrBL = rotrBL;
8183
8182
  // Right rotate for shift===32 (just swaps l&h)
8184
- const rotr32H = (h, l) => l;
8185
- const rotr32L = (h, l) => h;
8183
+ const rotr32H = (_h, l) => l;
8184
+ exports.rotr32H = rotr32H;
8185
+ const rotr32L = (h, _l) => h;
8186
+ exports.rotr32L = rotr32L;
8186
8187
  // Left rotate for Shift in [1, 32)
8187
8188
  const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
8189
+ exports.rotlSH = rotlSH;
8188
8190
  const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
8191
+ exports.rotlSL = rotlSL;
8189
8192
  // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
8190
8193
  const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
8194
+ exports.rotlBH = rotlBH;
8191
8195
  const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
8196
+ exports.rotlBL = rotlBL;
8192
8197
  // JS uses 32-bit signed integers for bitwise operations which means we cannot
8193
8198
  // simple take carry out of low bit sum by shift, we need to use division.
8194
- // Removing "export" has 5% perf penalty -_-
8195
8199
  function add(Ah, Al, Bh, Bl) {
8196
8200
  const l = (Al >>> 0) + (Bl >>> 0);
8197
8201
  return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
@@ -8199,14 +8203,20 @@ function add(Ah, Al, Bh, Bl) {
8199
8203
  exports.add = add;
8200
8204
  // Addition with more than 2 elements
8201
8205
  const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
8206
+ exports.add3L = add3L;
8202
8207
  const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
8208
+ exports.add3H = add3H;
8203
8209
  const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
8210
+ exports.add4L = add4L;
8204
8211
  const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
8212
+ exports.add4H = add4H;
8205
8213
  const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
8214
+ exports.add5L = add5L;
8206
8215
  const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
8216
+ exports.add5H = add5H;
8207
8217
  // prettier-ignore
8208
8218
  const u64 = {
8209
- fromBig, split, toBig: exports.toBig,
8219
+ fromBig, split, toBig,
8210
8220
  shrSH, shrSL,
8211
8221
  rotrSH, rotrSL, rotrBH, rotrBL,
8212
8222
  rotr32H, rotr32L,
@@ -8233,186 +8243,6 @@ exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? glob
8233
8243
 
8234
8244
  /***/ }),
8235
8245
 
8236
- /***/ "./node_modules/@noble/hashes/hkdf.js":
8237
- /*!********************************************!*\
8238
- !*** ./node_modules/@noble/hashes/hkdf.js ***!
8239
- \********************************************/
8240
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
8241
-
8242
- "use strict";
8243
-
8244
- Object.defineProperty(exports, "__esModule", ({ value: true }));
8245
- exports.hkdf = exports.expand = exports.extract = void 0;
8246
- const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/_assert.js");
8247
- const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
8248
- const hmac_js_1 = __webpack_require__(/*! ./hmac.js */ "./node_modules/@noble/hashes/hmac.js");
8249
- // HKDF (RFC 5869)
8250
- // https://soatok.blog/2021/11/17/understanding-hkdf/
8251
- /**
8252
- * HKDF-Extract(IKM, salt) -> PRK
8253
- * Arguments position differs from spec (IKM is first one, since it is not optional)
8254
- * @param hash
8255
- * @param ikm
8256
- * @param salt
8257
- * @returns
8258
- */
8259
- function extract(hash, ikm, salt) {
8260
- _assert_js_1.default.hash(hash);
8261
- // NOTE: some libraries treat zero-length array as 'not provided';
8262
- // we don't, since we have undefined as 'not provided'
8263
- // https://github.com/RustCrypto/KDFs/issues/15
8264
- if (salt === undefined)
8265
- salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros
8266
- return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm));
8267
- }
8268
- exports.extract = extract;
8269
- // HKDF-Expand(PRK, info, L) -> OKM
8270
- const HKDF_COUNTER = new Uint8Array([0]);
8271
- const EMPTY_BUFFER = new Uint8Array();
8272
- /**
8273
- * HKDF-expand from the spec.
8274
- * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
8275
- * @param info - optional context and application specific information (can be a zero-length string)
8276
- * @param length - length of output keying material in octets
8277
- */
8278
- function expand(hash, prk, info, length = 32) {
8279
- _assert_js_1.default.hash(hash);
8280
- _assert_js_1.default.number(length);
8281
- if (length > 255 * hash.outputLen)
8282
- throw new Error('Length should be <= 255*HashLen');
8283
- const blocks = Math.ceil(length / hash.outputLen);
8284
- if (info === undefined)
8285
- info = EMPTY_BUFFER;
8286
- // first L(ength) octets of T
8287
- const okm = new Uint8Array(blocks * hash.outputLen);
8288
- // Re-use HMAC instance between blocks
8289
- const HMAC = hmac_js_1.hmac.create(hash, prk);
8290
- const HMACTmp = HMAC._cloneInto();
8291
- const T = new Uint8Array(HMAC.outputLen);
8292
- for (let counter = 0; counter < blocks; counter++) {
8293
- HKDF_COUNTER[0] = counter + 1;
8294
- // T(0) = empty string (zero length)
8295
- // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
8296
- HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
8297
- .update(info)
8298
- .update(HKDF_COUNTER)
8299
- .digestInto(T);
8300
- okm.set(T, hash.outputLen * counter);
8301
- HMAC._cloneInto(HMACTmp);
8302
- }
8303
- HMAC.destroy();
8304
- HMACTmp.destroy();
8305
- T.fill(0);
8306
- HKDF_COUNTER.fill(0);
8307
- return okm.slice(0, length);
8308
- }
8309
- exports.expand = expand;
8310
- /**
8311
- * HKDF (RFC 5869): extract + expand in one step.
8312
- * @param hash - hash function that would be used (e.g. sha256)
8313
- * @param ikm - input keying material, the initial key
8314
- * @param salt - optional salt value (a non-secret random value)
8315
- * @param info - optional context and application specific information
8316
- * @param length - length of output keying material in octets
8317
- */
8318
- const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
8319
- exports.hkdf = hkdf;
8320
- //# sourceMappingURL=hkdf.js.map
8321
-
8322
- /***/ }),
8323
-
8324
- /***/ "./node_modules/@noble/hashes/hmac.js":
8325
- /*!********************************************!*\
8326
- !*** ./node_modules/@noble/hashes/hmac.js ***!
8327
- \********************************************/
8328
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
8329
-
8330
- "use strict";
8331
-
8332
- Object.defineProperty(exports, "__esModule", ({ value: true }));
8333
- exports.hmac = exports.HMAC = void 0;
8334
- const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/_assert.js");
8335
- const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
8336
- // HMAC (RFC 2104)
8337
- class HMAC extends utils_js_1.Hash {
8338
- constructor(hash, _key) {
8339
- super();
8340
- this.finished = false;
8341
- this.destroyed = false;
8342
- _assert_js_1.default.hash(hash);
8343
- const key = (0, utils_js_1.toBytes)(_key);
8344
- this.iHash = hash.create();
8345
- if (typeof this.iHash.update !== 'function')
8346
- throw new Error('Expected instance of class which extends utils.Hash');
8347
- this.blockLen = this.iHash.blockLen;
8348
- this.outputLen = this.iHash.outputLen;
8349
- const blockLen = this.blockLen;
8350
- const pad = new Uint8Array(blockLen);
8351
- // blockLen can be bigger than outputLen
8352
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
8353
- for (let i = 0; i < pad.length; i++)
8354
- pad[i] ^= 0x36;
8355
- this.iHash.update(pad);
8356
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
8357
- this.oHash = hash.create();
8358
- // Undo internal XOR && apply outer XOR
8359
- for (let i = 0; i < pad.length; i++)
8360
- pad[i] ^= 0x36 ^ 0x5c;
8361
- this.oHash.update(pad);
8362
- pad.fill(0);
8363
- }
8364
- update(buf) {
8365
- _assert_js_1.default.exists(this);
8366
- this.iHash.update(buf);
8367
- return this;
8368
- }
8369
- digestInto(out) {
8370
- _assert_js_1.default.exists(this);
8371
- _assert_js_1.default.bytes(out, this.outputLen);
8372
- this.finished = true;
8373
- this.iHash.digestInto(out);
8374
- this.oHash.update(out);
8375
- this.oHash.digestInto(out);
8376
- this.destroy();
8377
- }
8378
- digest() {
8379
- const out = new Uint8Array(this.oHash.outputLen);
8380
- this.digestInto(out);
8381
- return out;
8382
- }
8383
- _cloneInto(to) {
8384
- // Create new instance without calling constructor since key already in state and we don't know it.
8385
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
8386
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
8387
- to = to;
8388
- to.finished = finished;
8389
- to.destroyed = destroyed;
8390
- to.blockLen = blockLen;
8391
- to.outputLen = outputLen;
8392
- to.oHash = oHash._cloneInto(to.oHash);
8393
- to.iHash = iHash._cloneInto(to.iHash);
8394
- return to;
8395
- }
8396
- destroy() {
8397
- this.destroyed = true;
8398
- this.oHash.destroy();
8399
- this.iHash.destroy();
8400
- }
8401
- }
8402
- exports.HMAC = HMAC;
8403
- /**
8404
- * HMAC: RFC2104 message authentication code.
8405
- * @param hash - function that would be used e.g. sha256
8406
- * @param key - message key
8407
- * @param message - message data
8408
- */
8409
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
8410
- exports.hmac = hmac;
8411
- exports.hmac.create = (hash, key) => new HMAC(hash, key);
8412
- //# sourceMappingURL=hmac.js.map
8413
-
8414
- /***/ }),
8415
-
8416
8246
  /***/ "./node_modules/@noble/hashes/ripemd160.js":
8417
8247
  /*!*************************************************!*\
8418
8248
  !*** ./node_modules/@noble/hashes/ripemd160.js ***!
@@ -8427,25 +8257,29 @@ const _sha2_js_1 = __webpack_require__(/*! ./_sha2.js */ "./node_modules/@noble/
8427
8257
  const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
8428
8258
  // https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
8429
8259
  // https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
8430
- const Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
8431
- const Id = Uint8Array.from({ length: 16 }, (_, i) => i);
8432
- const Pi = Id.map((i) => (9 * i + 5) % 16);
8260
+ const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
8261
+ const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);
8262
+ const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);
8433
8263
  let idxL = [Id];
8434
8264
  let idxR = [Pi];
8435
8265
  for (let i = 0; i < 4; i++)
8436
8266
  for (let j of [idxL, idxR])
8437
8267
  j.push(j[i].map((k) => Rho[k]));
8438
- const shifts = [
8268
+ const shifts = /* @__PURE__ */ [
8439
8269
  [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
8440
8270
  [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
8441
8271
  [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
8442
8272
  [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
8443
8273
  [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
8444
8274
  ].map((i) => new Uint8Array(i));
8445
- const shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j]));
8446
- const shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j]));
8447
- const Kl = new Uint32Array([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]);
8448
- const Kr = new Uint32Array([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]);
8275
+ const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));
8276
+ const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));
8277
+ const Kl = /* @__PURE__ */ new Uint32Array([
8278
+ 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
8279
+ ]);
8280
+ const Kr = /* @__PURE__ */ new Uint32Array([
8281
+ 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
8282
+ ]);
8449
8283
  // The rotate left (circular left shift) operation for uint32
8450
8284
  const rotl = (word, shift) => (word << shift) | (word >>> (32 - shift));
8451
8285
  // It's called f() in spec.
@@ -8462,7 +8296,7 @@ function f(group, x, y, z) {
8462
8296
  return x ^ (y | ~z);
8463
8297
  }
8464
8298
  // Temporary buffer, not used to store anything between runs
8465
- const BUF = new Uint32Array(16);
8299
+ const BUF = /* @__PURE__ */ new Uint32Array(16);
8466
8300
  class RIPEMD160 extends _sha2_js_1.SHA2 {
8467
8301
  constructor() {
8468
8302
  super(64, 20, 8, true);
@@ -8539,6 +8373,8 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
8539
8373
  exports.sha224 = exports.sha256 = void 0;
8540
8374
  const _sha2_js_1 = __webpack_require__(/*! ./_sha2.js */ "./node_modules/@noble/hashes/_sha2.js");
8541
8375
  const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
8376
+ // SHA2-256 need to try 2^128 hashes to execute birthday attack.
8377
+ // BTC network is doing 2^67 hashes/sec as per early 2023.
8542
8378
  // Choice: a ? b : c
8543
8379
  const Chi = (a, b, c) => (a & b) ^ (~a & c);
8544
8380
  // Majority function, true if any two inpust is true
@@ -8546,7 +8382,7 @@ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
8546
8382
  // Round constants:
8547
8383
  // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
8548
8384
  // prettier-ignore
8549
- const SHA256_K = new Uint32Array([
8385
+ const SHA256_K = /* @__PURE__ */ new Uint32Array([
8550
8386
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
8551
8387
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8552
8388
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -8558,12 +8394,12 @@ const SHA256_K = new Uint32Array([
8558
8394
  ]);
8559
8395
  // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
8560
8396
  // prettier-ignore
8561
- const IV = new Uint32Array([
8397
+ const IV = /* @__PURE__ */ new Uint32Array([
8562
8398
  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
8563
8399
  ]);
8564
8400
  // Temporary buffer, not used to store anything between runs
8565
8401
  // Named this way because it matches specification.
8566
- const SHA256_W = new Uint32Array(64);
8402
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
8567
8403
  class SHA256 extends _sha2_js_1.SHA2 {
8568
8404
  constructor() {
8569
8405
  super(64, 32, 8, false);
@@ -8677,14 +8513,16 @@ exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 =
8677
8513
  const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/_assert.js");
8678
8514
  const _u64_js_1 = __webpack_require__(/*! ./_u64.js */ "./node_modules/@noble/hashes/_u64.js");
8679
8515
  const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/utils.js");
8516
+ // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
8517
+ // It's called a sponge function.
8680
8518
  // Various per round constants calculations
8681
8519
  const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];
8682
- const _0n = BigInt(0);
8683
- const _1n = BigInt(1);
8684
- const _2n = BigInt(2);
8685
- const _7n = BigInt(7);
8686
- const _256n = BigInt(256);
8687
- const _0x71n = BigInt(0x71);
8520
+ const _0n = /* @__PURE__ */ BigInt(0);
8521
+ const _1n = /* @__PURE__ */ BigInt(1);
8522
+ const _2n = /* @__PURE__ */ BigInt(2);
8523
+ const _7n = /* @__PURE__ */ BigInt(7);
8524
+ const _256n = /* @__PURE__ */ BigInt(256);
8525
+ const _0x71n = /* @__PURE__ */ BigInt(0x71);
8688
8526
  for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
8689
8527
  // Pi
8690
8528
  [x, y] = [y, (2 * x + 3 * y) % 5];
@@ -8696,14 +8534,14 @@ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
8696
8534
  for (let j = 0; j < 7; j++) {
8697
8535
  R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
8698
8536
  if (R & _2n)
8699
- t ^= _1n << ((_1n << BigInt(j)) - _1n);
8537
+ t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
8700
8538
  }
8701
8539
  _SHA3_IOTA.push(t);
8702
8540
  }
8703
- const [SHA3_IOTA_H, SHA3_IOTA_L] = _u64_js_1.default.split(_SHA3_IOTA, true);
8541
+ const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true);
8704
8542
  // Left rotation (without 0, 32, 64)
8705
- const rotlH = (h, l, s) => s > 32 ? _u64_js_1.default.rotlBH(h, l, s) : _u64_js_1.default.rotlSH(h, l, s);
8706
- const rotlL = (h, l, s) => s > 32 ? _u64_js_1.default.rotlBL(h, l, s) : _u64_js_1.default.rotlSL(h, l, s);
8543
+ const rotlH = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s));
8544
+ const rotlL = (h, l, s) => (s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s));
8707
8545
  // Same as keccakf1600, but allows to skip some rounds
8708
8546
  function keccakP(s, rounds = 24) {
8709
8547
  const B = new Uint32Array(5 * 2);
@@ -8765,7 +8603,7 @@ class Keccak extends utils_js_1.Hash {
8765
8603
  this.finished = false;
8766
8604
  this.destroyed = false;
8767
8605
  // Can be passed from user as dkLen
8768
- _assert_js_1.default.number(outputLen);
8606
+ (0, _assert_js_1.number)(outputLen);
8769
8607
  // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
8770
8608
  if (0 >= this.blockLen || this.blockLen >= 200)
8771
8609
  throw new Error('Sha3 supports only keccak-f1600 function');
@@ -8778,7 +8616,7 @@ class Keccak extends utils_js_1.Hash {
8778
8616
  this.pos = 0;
8779
8617
  }
8780
8618
  update(data) {
8781
- _assert_js_1.default.exists(this);
8619
+ (0, _assert_js_1.exists)(this);
8782
8620
  const { blockLen, state } = this;
8783
8621
  data = (0, utils_js_1.toBytes)(data);
8784
8622
  const len = data.length;
@@ -8804,8 +8642,8 @@ class Keccak extends utils_js_1.Hash {
8804
8642
  this.keccak();
8805
8643
  }
8806
8644
  writeInto(out) {
8807
- _assert_js_1.default.exists(this, false);
8808
- _assert_js_1.default.bytes(out);
8645
+ (0, _assert_js_1.exists)(this, false);
8646
+ (0, _assert_js_1.bytes)(out);
8809
8647
  this.finish();
8810
8648
  const bufferOut = this.state;
8811
8649
  const { blockLen } = this;
@@ -8826,11 +8664,11 @@ class Keccak extends utils_js_1.Hash {
8826
8664
  return this.writeInto(out);
8827
8665
  }
8828
8666
  xof(bytes) {
8829
- _assert_js_1.default.number(bytes);
8667
+ (0, _assert_js_1.number)(bytes);
8830
8668
  return this.xofInto(new Uint8Array(bytes));
8831
8669
  }
8832
8670
  digestInto(out) {
8833
- _assert_js_1.default.output(out, this);
8671
+ (0, _assert_js_1.output)(out, this);
8834
8672
  if (this.finished)
8835
8673
  throw new Error('digest() was already called');
8836
8674
  this.writeInto(out);
@@ -8920,7 +8758,7 @@ exports.rotr = rotr;
8920
8758
  exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
8921
8759
  if (!exports.isLE)
8922
8760
  throw new Error('Non little-endian hardware is not supported');
8923
- const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
8761
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
8924
8762
  /**
8925
8763
  * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
8926
8764
  */
@@ -9020,10 +8858,9 @@ class Hash {
9020
8858
  }
9021
8859
  }
9022
8860
  exports.Hash = Hash;
9023
- // Check if object doens't have custom constructor (like Uint8Array/Array)
9024
- const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
8861
+ const toStr = {}.toString;
9025
8862
  function checkOpts(defaults, opts) {
9026
- if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))
8863
+ if (opts !== undefined && toStr.call(opts) !== '[object Object]')
9027
8864
  throw new Error('Options should be object or undefined');
9028
8865
  const merged = Object.assign(defaults, opts);
9029
8866
  return merged;
@@ -73856,7 +73693,7 @@ module.exports = __toCommonJS(nostr_tools_exports);
73856
73693
 
73857
73694
  // pure.ts
73858
73695
  var import_secp256k1 = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/nostr-tools/node_modules/@noble/curves/secp256k1.js");
73859
- var import_utils2 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
73696
+ var import_utils2 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
73860
73697
 
73861
73698
  // core.ts
73862
73699
  var verifiedSymbol = Symbol("verified");
@@ -73897,7 +73734,7 @@ function sortEvents(events) {
73897
73734
  }
73898
73735
 
73899
73736
  // pure.ts
73900
- var import_sha256 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
73737
+ var import_sha256 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/nostr-tools/node_modules/@noble/hashes/sha256.js");
73901
73738
 
73902
73739
  // utils.ts
73903
73740
  var utils_exports = {};
@@ -73913,7 +73750,7 @@ __export(utils_exports, {
73913
73750
  utf8Decoder: () => utf8Decoder,
73914
73751
  utf8Encoder: () => utf8Encoder
73915
73752
  });
73916
- var import_utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
73753
+ var import_utils = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
73917
73754
  var utf8Decoder = new TextDecoder("utf-8");
73918
73755
  var utf8Encoder = new TextEncoder();
73919
73756
  function normalizeURL(url) {
@@ -75073,7 +74910,7 @@ __export(nip19_exports, {
75073
74910
  npubEncode: () => npubEncode,
75074
74911
  nsecEncode: () => nsecEncode
75075
74912
  });
75076
- var import_utils6 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
74913
+ var import_utils6 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
75077
74914
  var import_base = __webpack_require__(/*! @scure/base */ "./node_modules/nostr-tools/node_modules/@scure/base/lib/index.js");
75078
74915
  var NostrTypeGuard = {
75079
74916
  isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""),
@@ -75343,7 +75180,7 @@ __export(nip04_exports, {
75343
75180
  decrypt: () => decrypt,
75344
75181
  encrypt: () => encrypt
75345
75182
  });
75346
- var import_utils8 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
75183
+ var import_utils8 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
75347
75184
  var import_secp256k12 = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/nostr-tools/node_modules/@noble/curves/secp256k1.js");
75348
75185
  var import_aes = __webpack_require__(/*! @noble/ciphers/aes */ "./node_modules/@noble/ciphers/aes.js");
75349
75186
  var import_base2 = __webpack_require__(/*! @scure/base */ "./node_modules/nostr-tools/node_modules/@scure/base/lib/index.js");
@@ -75561,8 +75398,8 @@ __export(nip13_exports, {
75561
75398
  getPow: () => getPow,
75562
75399
  minePow: () => minePow
75563
75400
  });
75564
- var import_utils10 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
75565
- var import_sha2562 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
75401
+ var import_utils10 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
75402
+ var import_sha2562 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/nostr-tools/node_modules/@noble/hashes/sha256.js");
75566
75403
  function getPow(hex) {
75567
75404
  let count = 0;
75568
75405
  for (let i2 = 0; i2 < 64; i2 += 8) {
@@ -75633,10 +75470,10 @@ __export(nip44_exports, {
75633
75470
  var import_chacha = __webpack_require__(/*! @noble/ciphers/chacha */ "./node_modules/@noble/ciphers/chacha.js");
75634
75471
  var import_utils12 = __webpack_require__(/*! @noble/ciphers/utils */ "./node_modules/@noble/ciphers/utils.js");
75635
75472
  var import_secp256k13 = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/nostr-tools/node_modules/@noble/curves/secp256k1.js");
75636
- var import_hkdf = __webpack_require__(/*! @noble/hashes/hkdf */ "./node_modules/@noble/hashes/hkdf.js");
75637
- var import_hmac = __webpack_require__(/*! @noble/hashes/hmac */ "./node_modules/@noble/hashes/hmac.js");
75638
- var import_sha2563 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
75639
- var import_utils13 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
75473
+ var import_hkdf = __webpack_require__(/*! @noble/hashes/hkdf */ "./node_modules/nostr-tools/node_modules/@noble/hashes/hkdf.js");
75474
+ var import_hmac = __webpack_require__(/*! @noble/hashes/hmac */ "./node_modules/nostr-tools/node_modules/@noble/hashes/hmac.js");
75475
+ var import_sha2563 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/nostr-tools/node_modules/@noble/hashes/sha256.js");
75476
+ var import_utils13 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
75640
75477
  var import_base3 = __webpack_require__(/*! @scure/base */ "./node_modules/nostr-tools/node_modules/@scure/base/lib/index.js");
75641
75478
  var minPlaintextSize = 1;
75642
75479
  var maxPlaintextSize = 65535;
@@ -76469,8 +76306,8 @@ __export(nip98_exports, {
76469
76306
  validateEventUrlTag: () => validateEventUrlTag,
76470
76307
  validateToken: () => validateToken
76471
76308
  });
76472
- var import_sha2564 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/sha256.js");
76473
- var import_utils16 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/utils.js");
76309
+ var import_sha2564 = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/nostr-tools/node_modules/@noble/hashes/sha256.js");
76310
+ var import_utils16 = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
76474
76311
  var import_base5 = __webpack_require__(/*! @scure/base */ "./node_modules/nostr-tools/node_modules/@scure/base/lib/index.js");
76475
76312
  var _authorizationScheme = "Nostr ";
76476
76313
  async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) {
@@ -79667,6 +79504,713 @@ exports.encodeToCurve = (() => htf.encodeToCurve)();
79667
79504
 
79668
79505
  /***/ }),
79669
79506
 
79507
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/_assert.js":
79508
+ /*!************************************************************************!*\
79509
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/_assert.js ***!
79510
+ \************************************************************************/
79511
+ /***/ ((__unused_webpack_module, exports) => {
79512
+
79513
+ "use strict";
79514
+
79515
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
79516
+ exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0;
79517
+ function number(n) {
79518
+ if (!Number.isSafeInteger(n) || n < 0)
79519
+ throw new Error(`Wrong positive integer: ${n}`);
79520
+ }
79521
+ exports.number = number;
79522
+ function bool(b) {
79523
+ if (typeof b !== 'boolean')
79524
+ throw new Error(`Expected boolean, not ${b}`);
79525
+ }
79526
+ exports.bool = bool;
79527
+ function bytes(b, ...lengths) {
79528
+ if (!(b instanceof Uint8Array))
79529
+ throw new Error('Expected Uint8Array');
79530
+ if (lengths.length > 0 && !lengths.includes(b.length))
79531
+ throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
79532
+ }
79533
+ exports.bytes = bytes;
79534
+ function hash(hash) {
79535
+ if (typeof hash !== 'function' || typeof hash.create !== 'function')
79536
+ throw new Error('Hash should be wrapped by utils.wrapConstructor');
79537
+ number(hash.outputLen);
79538
+ number(hash.blockLen);
79539
+ }
79540
+ exports.hash = hash;
79541
+ function exists(instance, checkFinished = true) {
79542
+ if (instance.destroyed)
79543
+ throw new Error('Hash instance has been destroyed');
79544
+ if (checkFinished && instance.finished)
79545
+ throw new Error('Hash#digest() has already been called');
79546
+ }
79547
+ exports.exists = exists;
79548
+ function output(out, instance) {
79549
+ bytes(out);
79550
+ const min = instance.outputLen;
79551
+ if (out.length < min) {
79552
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
79553
+ }
79554
+ }
79555
+ exports.output = output;
79556
+ const assert = {
79557
+ number,
79558
+ bool,
79559
+ bytes,
79560
+ hash,
79561
+ exists,
79562
+ output,
79563
+ };
79564
+ exports["default"] = assert;
79565
+ //# sourceMappingURL=_assert.js.map
79566
+
79567
+ /***/ }),
79568
+
79569
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/_sha2.js":
79570
+ /*!**********************************************************************!*\
79571
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/_sha2.js ***!
79572
+ \**********************************************************************/
79573
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
79574
+
79575
+ "use strict";
79576
+
79577
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
79578
+ exports.SHA2 = void 0;
79579
+ const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/_assert.js");
79580
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
79581
+ // Polyfill for Safari 14
79582
+ function setBigUint64(view, byteOffset, value, isLE) {
79583
+ if (typeof view.setBigUint64 === 'function')
79584
+ return view.setBigUint64(byteOffset, value, isLE);
79585
+ const _32n = BigInt(32);
79586
+ const _u32_max = BigInt(0xffffffff);
79587
+ const wh = Number((value >> _32n) & _u32_max);
79588
+ const wl = Number(value & _u32_max);
79589
+ const h = isLE ? 4 : 0;
79590
+ const l = isLE ? 0 : 4;
79591
+ view.setUint32(byteOffset + h, wh, isLE);
79592
+ view.setUint32(byteOffset + l, wl, isLE);
79593
+ }
79594
+ // Base SHA2 class (RFC 6234)
79595
+ class SHA2 extends utils_js_1.Hash {
79596
+ constructor(blockLen, outputLen, padOffset, isLE) {
79597
+ super();
79598
+ this.blockLen = blockLen;
79599
+ this.outputLen = outputLen;
79600
+ this.padOffset = padOffset;
79601
+ this.isLE = isLE;
79602
+ this.finished = false;
79603
+ this.length = 0;
79604
+ this.pos = 0;
79605
+ this.destroyed = false;
79606
+ this.buffer = new Uint8Array(blockLen);
79607
+ this.view = (0, utils_js_1.createView)(this.buffer);
79608
+ }
79609
+ update(data) {
79610
+ _assert_js_1.default.exists(this);
79611
+ const { view, buffer, blockLen } = this;
79612
+ data = (0, utils_js_1.toBytes)(data);
79613
+ const len = data.length;
79614
+ for (let pos = 0; pos < len;) {
79615
+ const take = Math.min(blockLen - this.pos, len - pos);
79616
+ // Fast path: we have at least one block in input, cast it to view and process
79617
+ if (take === blockLen) {
79618
+ const dataView = (0, utils_js_1.createView)(data);
79619
+ for (; blockLen <= len - pos; pos += blockLen)
79620
+ this.process(dataView, pos);
79621
+ continue;
79622
+ }
79623
+ buffer.set(data.subarray(pos, pos + take), this.pos);
79624
+ this.pos += take;
79625
+ pos += take;
79626
+ if (this.pos === blockLen) {
79627
+ this.process(view, 0);
79628
+ this.pos = 0;
79629
+ }
79630
+ }
79631
+ this.length += data.length;
79632
+ this.roundClean();
79633
+ return this;
79634
+ }
79635
+ digestInto(out) {
79636
+ _assert_js_1.default.exists(this);
79637
+ _assert_js_1.default.output(out, this);
79638
+ this.finished = true;
79639
+ // Padding
79640
+ // We can avoid allocation of buffer for padding completely if it
79641
+ // was previously not allocated here. But it won't change performance.
79642
+ const { buffer, view, blockLen, isLE } = this;
79643
+ let { pos } = this;
79644
+ // append the bit '1' to the message
79645
+ buffer[pos++] = 0b10000000;
79646
+ this.buffer.subarray(pos).fill(0);
79647
+ // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
79648
+ if (this.padOffset > blockLen - pos) {
79649
+ this.process(view, 0);
79650
+ pos = 0;
79651
+ }
79652
+ // Pad until full block byte with zeros
79653
+ for (let i = pos; i < blockLen; i++)
79654
+ buffer[i] = 0;
79655
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
79656
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
79657
+ // So we just write lowest 64 bits of that value.
79658
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
79659
+ this.process(view, 0);
79660
+ const oview = (0, utils_js_1.createView)(out);
79661
+ const len = this.outputLen;
79662
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
79663
+ if (len % 4)
79664
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
79665
+ const outLen = len / 4;
79666
+ const state = this.get();
79667
+ if (outLen > state.length)
79668
+ throw new Error('_sha2: outputLen bigger than state');
79669
+ for (let i = 0; i < outLen; i++)
79670
+ oview.setUint32(4 * i, state[i], isLE);
79671
+ }
79672
+ digest() {
79673
+ const { buffer, outputLen } = this;
79674
+ this.digestInto(buffer);
79675
+ const res = buffer.slice(0, outputLen);
79676
+ this.destroy();
79677
+ return res;
79678
+ }
79679
+ _cloneInto(to) {
79680
+ to || (to = new this.constructor());
79681
+ to.set(...this.get());
79682
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
79683
+ to.length = length;
79684
+ to.pos = pos;
79685
+ to.finished = finished;
79686
+ to.destroyed = destroyed;
79687
+ if (length % blockLen)
79688
+ to.buffer.set(buffer);
79689
+ return to;
79690
+ }
79691
+ }
79692
+ exports.SHA2 = SHA2;
79693
+ //# sourceMappingURL=_sha2.js.map
79694
+
79695
+ /***/ }),
79696
+
79697
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/crypto.js":
79698
+ /*!***********************************************************************!*\
79699
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/crypto.js ***!
79700
+ \***********************************************************************/
79701
+ /***/ ((__unused_webpack_module, exports) => {
79702
+
79703
+ "use strict";
79704
+
79705
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
79706
+ exports.crypto = void 0;
79707
+ exports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
79708
+ //# sourceMappingURL=crypto.js.map
79709
+
79710
+ /***/ }),
79711
+
79712
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/hkdf.js":
79713
+ /*!*********************************************************************!*\
79714
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/hkdf.js ***!
79715
+ \*********************************************************************/
79716
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
79717
+
79718
+ "use strict";
79719
+
79720
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
79721
+ exports.hkdf = exports.expand = exports.extract = void 0;
79722
+ const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/_assert.js");
79723
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
79724
+ const hmac_js_1 = __webpack_require__(/*! ./hmac.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/hmac.js");
79725
+ // HKDF (RFC 5869)
79726
+ // https://soatok.blog/2021/11/17/understanding-hkdf/
79727
+ /**
79728
+ * HKDF-Extract(IKM, salt) -> PRK
79729
+ * Arguments position differs from spec (IKM is first one, since it is not optional)
79730
+ * @param hash
79731
+ * @param ikm
79732
+ * @param salt
79733
+ * @returns
79734
+ */
79735
+ function extract(hash, ikm, salt) {
79736
+ _assert_js_1.default.hash(hash);
79737
+ // NOTE: some libraries treat zero-length array as 'not provided';
79738
+ // we don't, since we have undefined as 'not provided'
79739
+ // https://github.com/RustCrypto/KDFs/issues/15
79740
+ if (salt === undefined)
79741
+ salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros
79742
+ return (0, hmac_js_1.hmac)(hash, (0, utils_js_1.toBytes)(salt), (0, utils_js_1.toBytes)(ikm));
79743
+ }
79744
+ exports.extract = extract;
79745
+ // HKDF-Expand(PRK, info, L) -> OKM
79746
+ const HKDF_COUNTER = new Uint8Array([0]);
79747
+ const EMPTY_BUFFER = new Uint8Array();
79748
+ /**
79749
+ * HKDF-expand from the spec.
79750
+ * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
79751
+ * @param info - optional context and application specific information (can be a zero-length string)
79752
+ * @param length - length of output keying material in octets
79753
+ */
79754
+ function expand(hash, prk, info, length = 32) {
79755
+ _assert_js_1.default.hash(hash);
79756
+ _assert_js_1.default.number(length);
79757
+ if (length > 255 * hash.outputLen)
79758
+ throw new Error('Length should be <= 255*HashLen');
79759
+ const blocks = Math.ceil(length / hash.outputLen);
79760
+ if (info === undefined)
79761
+ info = EMPTY_BUFFER;
79762
+ // first L(ength) octets of T
79763
+ const okm = new Uint8Array(blocks * hash.outputLen);
79764
+ // Re-use HMAC instance between blocks
79765
+ const HMAC = hmac_js_1.hmac.create(hash, prk);
79766
+ const HMACTmp = HMAC._cloneInto();
79767
+ const T = new Uint8Array(HMAC.outputLen);
79768
+ for (let counter = 0; counter < blocks; counter++) {
79769
+ HKDF_COUNTER[0] = counter + 1;
79770
+ // T(0) = empty string (zero length)
79771
+ // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
79772
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
79773
+ .update(info)
79774
+ .update(HKDF_COUNTER)
79775
+ .digestInto(T);
79776
+ okm.set(T, hash.outputLen * counter);
79777
+ HMAC._cloneInto(HMACTmp);
79778
+ }
79779
+ HMAC.destroy();
79780
+ HMACTmp.destroy();
79781
+ T.fill(0);
79782
+ HKDF_COUNTER.fill(0);
79783
+ return okm.slice(0, length);
79784
+ }
79785
+ exports.expand = expand;
79786
+ /**
79787
+ * HKDF (RFC 5869): extract + expand in one step.
79788
+ * @param hash - hash function that would be used (e.g. sha256)
79789
+ * @param ikm - input keying material, the initial key
79790
+ * @param salt - optional salt value (a non-secret random value)
79791
+ * @param info - optional context and application specific information
79792
+ * @param length - length of output keying material in octets
79793
+ */
79794
+ const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
79795
+ exports.hkdf = hkdf;
79796
+ //# sourceMappingURL=hkdf.js.map
79797
+
79798
+ /***/ }),
79799
+
79800
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/hmac.js":
79801
+ /*!*********************************************************************!*\
79802
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/hmac.js ***!
79803
+ \*********************************************************************/
79804
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
79805
+
79806
+ "use strict";
79807
+
79808
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
79809
+ exports.hmac = exports.HMAC = void 0;
79810
+ const _assert_js_1 = __webpack_require__(/*! ./_assert.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/_assert.js");
79811
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
79812
+ // HMAC (RFC 2104)
79813
+ class HMAC extends utils_js_1.Hash {
79814
+ constructor(hash, _key) {
79815
+ super();
79816
+ this.finished = false;
79817
+ this.destroyed = false;
79818
+ _assert_js_1.default.hash(hash);
79819
+ const key = (0, utils_js_1.toBytes)(_key);
79820
+ this.iHash = hash.create();
79821
+ if (typeof this.iHash.update !== 'function')
79822
+ throw new Error('Expected instance of class which extends utils.Hash');
79823
+ this.blockLen = this.iHash.blockLen;
79824
+ this.outputLen = this.iHash.outputLen;
79825
+ const blockLen = this.blockLen;
79826
+ const pad = new Uint8Array(blockLen);
79827
+ // blockLen can be bigger than outputLen
79828
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
79829
+ for (let i = 0; i < pad.length; i++)
79830
+ pad[i] ^= 0x36;
79831
+ this.iHash.update(pad);
79832
+ // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
79833
+ this.oHash = hash.create();
79834
+ // Undo internal XOR && apply outer XOR
79835
+ for (let i = 0; i < pad.length; i++)
79836
+ pad[i] ^= 0x36 ^ 0x5c;
79837
+ this.oHash.update(pad);
79838
+ pad.fill(0);
79839
+ }
79840
+ update(buf) {
79841
+ _assert_js_1.default.exists(this);
79842
+ this.iHash.update(buf);
79843
+ return this;
79844
+ }
79845
+ digestInto(out) {
79846
+ _assert_js_1.default.exists(this);
79847
+ _assert_js_1.default.bytes(out, this.outputLen);
79848
+ this.finished = true;
79849
+ this.iHash.digestInto(out);
79850
+ this.oHash.update(out);
79851
+ this.oHash.digestInto(out);
79852
+ this.destroy();
79853
+ }
79854
+ digest() {
79855
+ const out = new Uint8Array(this.oHash.outputLen);
79856
+ this.digestInto(out);
79857
+ return out;
79858
+ }
79859
+ _cloneInto(to) {
79860
+ // Create new instance without calling constructor since key already in state and we don't know it.
79861
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
79862
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
79863
+ to = to;
79864
+ to.finished = finished;
79865
+ to.destroyed = destroyed;
79866
+ to.blockLen = blockLen;
79867
+ to.outputLen = outputLen;
79868
+ to.oHash = oHash._cloneInto(to.oHash);
79869
+ to.iHash = iHash._cloneInto(to.iHash);
79870
+ return to;
79871
+ }
79872
+ destroy() {
79873
+ this.destroyed = true;
79874
+ this.oHash.destroy();
79875
+ this.iHash.destroy();
79876
+ }
79877
+ }
79878
+ exports.HMAC = HMAC;
79879
+ /**
79880
+ * HMAC: RFC2104 message authentication code.
79881
+ * @param hash - function that would be used e.g. sha256
79882
+ * @param key - message key
79883
+ * @param message - message data
79884
+ */
79885
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
79886
+ exports.hmac = hmac;
79887
+ exports.hmac.create = (hash, key) => new HMAC(hash, key);
79888
+ //# sourceMappingURL=hmac.js.map
79889
+
79890
+ /***/ }),
79891
+
79892
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/sha256.js":
79893
+ /*!***********************************************************************!*\
79894
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/sha256.js ***!
79895
+ \***********************************************************************/
79896
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
79897
+
79898
+ "use strict";
79899
+
79900
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
79901
+ exports.sha224 = exports.sha256 = void 0;
79902
+ const _sha2_js_1 = __webpack_require__(/*! ./_sha2.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/_sha2.js");
79903
+ const utils_js_1 = __webpack_require__(/*! ./utils.js */ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js");
79904
+ // Choice: a ? b : c
79905
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
79906
+ // Majority function, true if any two inpust is true
79907
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
79908
+ // Round constants:
79909
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
79910
+ // prettier-ignore
79911
+ const SHA256_K = new Uint32Array([
79912
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
79913
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
79914
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
79915
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
79916
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
79917
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
79918
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
79919
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
79920
+ ]);
79921
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
79922
+ // prettier-ignore
79923
+ const IV = new Uint32Array([
79924
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
79925
+ ]);
79926
+ // Temporary buffer, not used to store anything between runs
79927
+ // Named this way because it matches specification.
79928
+ const SHA256_W = new Uint32Array(64);
79929
+ class SHA256 extends _sha2_js_1.SHA2 {
79930
+ constructor() {
79931
+ super(64, 32, 8, false);
79932
+ // We cannot use array here since array allows indexing by variable
79933
+ // which means optimizer/compiler cannot use registers.
79934
+ this.A = IV[0] | 0;
79935
+ this.B = IV[1] | 0;
79936
+ this.C = IV[2] | 0;
79937
+ this.D = IV[3] | 0;
79938
+ this.E = IV[4] | 0;
79939
+ this.F = IV[5] | 0;
79940
+ this.G = IV[6] | 0;
79941
+ this.H = IV[7] | 0;
79942
+ }
79943
+ get() {
79944
+ const { A, B, C, D, E, F, G, H } = this;
79945
+ return [A, B, C, D, E, F, G, H];
79946
+ }
79947
+ // prettier-ignore
79948
+ set(A, B, C, D, E, F, G, H) {
79949
+ this.A = A | 0;
79950
+ this.B = B | 0;
79951
+ this.C = C | 0;
79952
+ this.D = D | 0;
79953
+ this.E = E | 0;
79954
+ this.F = F | 0;
79955
+ this.G = G | 0;
79956
+ this.H = H | 0;
79957
+ }
79958
+ process(view, offset) {
79959
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
79960
+ for (let i = 0; i < 16; i++, offset += 4)
79961
+ SHA256_W[i] = view.getUint32(offset, false);
79962
+ for (let i = 16; i < 64; i++) {
79963
+ const W15 = SHA256_W[i - 15];
79964
+ const W2 = SHA256_W[i - 2];
79965
+ const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3);
79966
+ const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10);
79967
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
79968
+ }
79969
+ // Compression function main loop, 64 rounds
79970
+ let { A, B, C, D, E, F, G, H } = this;
79971
+ for (let i = 0; i < 64; i++) {
79972
+ const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25);
79973
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
79974
+ const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22);
79975
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
79976
+ H = G;
79977
+ G = F;
79978
+ F = E;
79979
+ E = (D + T1) | 0;
79980
+ D = C;
79981
+ C = B;
79982
+ B = A;
79983
+ A = (T1 + T2) | 0;
79984
+ }
79985
+ // Add the compressed chunk to the current hash value
79986
+ A = (A + this.A) | 0;
79987
+ B = (B + this.B) | 0;
79988
+ C = (C + this.C) | 0;
79989
+ D = (D + this.D) | 0;
79990
+ E = (E + this.E) | 0;
79991
+ F = (F + this.F) | 0;
79992
+ G = (G + this.G) | 0;
79993
+ H = (H + this.H) | 0;
79994
+ this.set(A, B, C, D, E, F, G, H);
79995
+ }
79996
+ roundClean() {
79997
+ SHA256_W.fill(0);
79998
+ }
79999
+ destroy() {
80000
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
80001
+ this.buffer.fill(0);
80002
+ }
80003
+ }
80004
+ // Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
80005
+ class SHA224 extends SHA256 {
80006
+ constructor() {
80007
+ super();
80008
+ this.A = 0xc1059ed8 | 0;
80009
+ this.B = 0x367cd507 | 0;
80010
+ this.C = 0x3070dd17 | 0;
80011
+ this.D = 0xf70e5939 | 0;
80012
+ this.E = 0xffc00b31 | 0;
80013
+ this.F = 0x68581511 | 0;
80014
+ this.G = 0x64f98fa7 | 0;
80015
+ this.H = 0xbefa4fa4 | 0;
80016
+ this.outputLen = 28;
80017
+ }
80018
+ }
80019
+ /**
80020
+ * SHA2-256 hash function
80021
+ * @param message - data that would be hashed
80022
+ */
80023
+ exports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());
80024
+ exports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224());
80025
+ //# sourceMappingURL=sha256.js.map
80026
+
80027
+ /***/ }),
80028
+
80029
+ /***/ "./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js":
80030
+ /*!**********************************************************************!*\
80031
+ !*** ./node_modules/nostr-tools/node_modules/@noble/hashes/utils.js ***!
80032
+ \**********************************************************************/
80033
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
80034
+
80035
+ "use strict";
80036
+
80037
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
80038
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
80039
+ exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0;
80040
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
80041
+ // node.js versions earlier than v19 don't declare it in global scope.
80042
+ // For node.js, package.json#exports field mapping rewrites import
80043
+ // from `crypto` to `cryptoNode`, which imports native module.
80044
+ // Makes the utils un-importable in browsers without a bundler.
80045
+ // Once node.js 18 is deprecated, we can just drop the import.
80046
+ const crypto_1 = __webpack_require__(/*! @noble/hashes/crypto */ "./node_modules/nostr-tools/node_modules/@noble/hashes/crypto.js");
80047
+ const u8a = (a) => a instanceof Uint8Array;
80048
+ // Cast array to different type
80049
+ const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
80050
+ exports.u8 = u8;
80051
+ const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
80052
+ exports.u32 = u32;
80053
+ // Cast array to view
80054
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
80055
+ exports.createView = createView;
80056
+ // The rotate right (circular right shift) operation for uint32
80057
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
80058
+ exports.rotr = rotr;
80059
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
80060
+ // early-throw an error because we don't support BE yet.
80061
+ exports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
80062
+ if (!exports.isLE)
80063
+ throw new Error('Non little-endian hardware is not supported');
80064
+ const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
80065
+ /**
80066
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
80067
+ */
80068
+ function bytesToHex(bytes) {
80069
+ if (!u8a(bytes))
80070
+ throw new Error('Uint8Array expected');
80071
+ // pre-caching improves the speed 6x
80072
+ let hex = '';
80073
+ for (let i = 0; i < bytes.length; i++) {
80074
+ hex += hexes[bytes[i]];
80075
+ }
80076
+ return hex;
80077
+ }
80078
+ exports.bytesToHex = bytesToHex;
80079
+ /**
80080
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
80081
+ */
80082
+ function hexToBytes(hex) {
80083
+ if (typeof hex !== 'string')
80084
+ throw new Error('hex string expected, got ' + typeof hex);
80085
+ const len = hex.length;
80086
+ if (len % 2)
80087
+ throw new Error('padded hex string expected, got unpadded hex of length ' + len);
80088
+ const array = new Uint8Array(len / 2);
80089
+ for (let i = 0; i < array.length; i++) {
80090
+ const j = i * 2;
80091
+ const hexByte = hex.slice(j, j + 2);
80092
+ const byte = Number.parseInt(hexByte, 16);
80093
+ if (Number.isNaN(byte) || byte < 0)
80094
+ throw new Error('Invalid byte sequence');
80095
+ array[i] = byte;
80096
+ }
80097
+ return array;
80098
+ }
80099
+ exports.hexToBytes = hexToBytes;
80100
+ // There is no setImmediate in browser and setTimeout is slow.
80101
+ // call of async fn will return Promise, which will be fullfiled only on
80102
+ // next scheduler queue processing step and this is exactly what we need.
80103
+ const nextTick = async () => { };
80104
+ exports.nextTick = nextTick;
80105
+ // Returns control to thread each 'tick' ms to avoid blocking
80106
+ async function asyncLoop(iters, tick, cb) {
80107
+ let ts = Date.now();
80108
+ for (let i = 0; i < iters; i++) {
80109
+ cb(i);
80110
+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
80111
+ const diff = Date.now() - ts;
80112
+ if (diff >= 0 && diff < tick)
80113
+ continue;
80114
+ await (0, exports.nextTick)();
80115
+ ts += diff;
80116
+ }
80117
+ }
80118
+ exports.asyncLoop = asyncLoop;
80119
+ /**
80120
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
80121
+ */
80122
+ function utf8ToBytes(str) {
80123
+ if (typeof str !== 'string')
80124
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
80125
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
80126
+ }
80127
+ exports.utf8ToBytes = utf8ToBytes;
80128
+ /**
80129
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
80130
+ * Warning: when Uint8Array is passed, it would NOT get copied.
80131
+ * Keep in mind for future mutable operations.
80132
+ */
80133
+ function toBytes(data) {
80134
+ if (typeof data === 'string')
80135
+ data = utf8ToBytes(data);
80136
+ if (!u8a(data))
80137
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
80138
+ return data;
80139
+ }
80140
+ exports.toBytes = toBytes;
80141
+ /**
80142
+ * Copies several Uint8Arrays into one.
80143
+ */
80144
+ function concatBytes(...arrays) {
80145
+ const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
80146
+ let pad = 0; // walk through each item, ensure they have proper type
80147
+ arrays.forEach((a) => {
80148
+ if (!u8a(a))
80149
+ throw new Error('Uint8Array expected');
80150
+ r.set(a, pad);
80151
+ pad += a.length;
80152
+ });
80153
+ return r;
80154
+ }
80155
+ exports.concatBytes = concatBytes;
80156
+ // For runtime check if class implements interface
80157
+ class Hash {
80158
+ // Safe version that clones internal state
80159
+ clone() {
80160
+ return this._cloneInto();
80161
+ }
80162
+ }
80163
+ exports.Hash = Hash;
80164
+ // Check if object doens't have custom constructor (like Uint8Array/Array)
80165
+ const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
80166
+ function checkOpts(defaults, opts) {
80167
+ if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))
80168
+ throw new Error('Options should be object or undefined');
80169
+ const merged = Object.assign(defaults, opts);
80170
+ return merged;
80171
+ }
80172
+ exports.checkOpts = checkOpts;
80173
+ function wrapConstructor(hashCons) {
80174
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
80175
+ const tmp = hashCons();
80176
+ hashC.outputLen = tmp.outputLen;
80177
+ hashC.blockLen = tmp.blockLen;
80178
+ hashC.create = () => hashCons();
80179
+ return hashC;
80180
+ }
80181
+ exports.wrapConstructor = wrapConstructor;
80182
+ function wrapConstructorWithOpts(hashCons) {
80183
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
80184
+ const tmp = hashCons({});
80185
+ hashC.outputLen = tmp.outputLen;
80186
+ hashC.blockLen = tmp.blockLen;
80187
+ hashC.create = (opts) => hashCons(opts);
80188
+ return hashC;
80189
+ }
80190
+ exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
80191
+ function wrapXOFConstructorWithOpts(hashCons) {
80192
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
80193
+ const tmp = hashCons({});
80194
+ hashC.outputLen = tmp.outputLen;
80195
+ hashC.blockLen = tmp.blockLen;
80196
+ hashC.create = (opts) => hashCons(opts);
80197
+ return hashC;
80198
+ }
80199
+ exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;
80200
+ /**
80201
+ * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
80202
+ */
80203
+ function randomBytes(bytesLength = 32) {
80204
+ if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
80205
+ return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
80206
+ }
80207
+ throw new Error('crypto.getRandomValues must be defined');
80208
+ }
80209
+ exports.randomBytes = randomBytes;
80210
+ //# sourceMappingURL=utils.js.map
80211
+
80212
+ /***/ }),
80213
+
79670
80214
  /***/ "./node_modules/nostr-tools/node_modules/@scure/base/lib/index.js":
79671
80215
  /*!************************************************************************!*\
79672
80216
  !*** ./node_modules/nostr-tools/node_modules/@scure/base/lib/index.js ***!
@@ -98485,1307 +99029,6 @@ module.exports = function whichTypedArray(value) {
98485
99029
  };
98486
99030
 
98487
99031
 
98488
- /***/ }),
98489
-
98490
- /***/ "./ship/examples/messenger-cli.ts":
98491
- /*!****************************************!*\
98492
- !*** ./ship/examples/messenger-cli.ts ***!
98493
- \****************************************/
98494
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
98495
-
98496
- "use strict";
98497
- /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "./node_modules/process/browser.js");
98498
- /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js")["Buffer"];
98499
- //#!/usr/bin/env node
98500
-
98501
- /**
98502
- * Shogun Chat - CLI Interface
98503
- *
98504
- * End-to-end encrypted decentralized chat
98505
- * Simple and functional CLI interface
98506
- */
98507
- Object.defineProperty(exports, "__esModule", ({ value: true }));
98508
- exports.MessengerCLI = void 0;
98509
- const SHIP_01_1 = __webpack_require__(/*! ../implementation/SHIP_01 */ "./ship/implementation/SHIP_01.ts");
98510
- // Only import readline in Node.js environment
98511
- let readline;
98512
- try {
98513
- if (false) // removed by dead control flow
98514
- {}
98515
- }
98516
- catch (e) {
98517
- // Browser environment - readline not available
98518
- }
98519
- // ============================================================================
98520
- // COLORS
98521
- // ============================================================================
98522
- const colors = {
98523
- reset: "\x1b[0m",
98524
- bold: "\x1b[1m",
98525
- dim: "\x1b[2m",
98526
- red: "\x1b[31m",
98527
- green: "\x1b[32m",
98528
- yellow: "\x1b[33m",
98529
- blue: "\x1b[34m",
98530
- magenta: "\x1b[35m",
98531
- cyan: "\x1b[36m",
98532
- white: "\x1b[37m",
98533
- gray: "\x1b[90m",
98534
- };
98535
- const c = (color, text) => `${colors[color]}${text}${colors.reset}`;
98536
- // ============================================================================
98537
- // CHAT CLI
98538
- // ============================================================================
98539
- class MessengerCLI {
98540
- constructor() {
98541
- this.currentUser = "";
98542
- this.recipient = "";
98543
- this.derivedAddress = "";
98544
- this.isAuthenticated = false;
98545
- // Initialize app in all environments (needed for TypeScript)
98546
- this.app = new SHIP_01_1.SHIP_01({
98547
- gunOptions: {
98548
- peers: [
98549
- "https://peer.wallie.io/gun",
98550
- "https://v5g5jseqhgkp43lppgregcfbvi.srv.us/gun",
98551
- "https://relay.shogun-eco.xyz/gun",
98552
- ],
98553
- radisk: true,
98554
- localStorage: false,
98555
- },
98556
- });
98557
- // Don't initialize readline in browser environment
98558
- if (true) {
98559
- console.warn('MessengerCLI is designed for Node.js CLI usage only');
98560
- return;
98561
- }
98562
- // removed by dead control flow
98563
-
98564
- // removed by dead control flow
98565
-
98566
- }
98567
- // ========================================================================
98568
- // SETUP
98569
- // ========================================================================
98570
- setupHandlers() {
98571
- this.rl.on("line", async (line) => {
98572
- const input = line.trim();
98573
- if (!input) {
98574
- this.rl.prompt();
98575
- return;
98576
- }
98577
- if (input.startsWith("/")) {
98578
- await this.handleCommand(input);
98579
- }
98580
- else {
98581
- await this.sendMessage(input);
98582
- }
98583
- this.rl.prompt();
98584
- });
98585
- this.rl.on("close", () => {
98586
- console.log("\n" + c("yellow", "👋 Arrivederci!"));
98587
- process.exit(0);
98588
- });
98589
- // Ctrl+C handler
98590
- process.on("SIGINT", () => {
98591
- this.rl.close();
98592
- });
98593
- }
98594
- // ========================================================================
98595
- // UTILITIES
98596
- // ========================================================================
98597
- async withTimeout(promise, timeoutMs, errorMessage) {
98598
- return Promise.race([
98599
- promise,
98600
- new Promise((_, reject) => setTimeout(() => reject(new Error(errorMessage)), timeoutMs)),
98601
- ]);
98602
- }
98603
- // ========================================================================
98604
- // AUTH
98605
- // ========================================================================
98606
- async login(username, password) {
98607
- console.log(c("cyan", "🔐 Login in corso..."));
98608
- // Loading indicator
98609
- const loadingInterval = setInterval(() => {
98610
- process.stdout.write(c("gray", "."));
98611
- }, 500);
98612
- try {
98613
- // Prova login con timeout
98614
- let result = await this.withTimeout(this.app.login(username, password), 15000, "Login timeout - verifica connessione ai peers");
98615
- clearInterval(loadingInterval);
98616
- console.log(""); // Nuova linea dopo i dots
98617
- // Se fallisce, prova signup
98618
- if (!result.success) {
98619
- console.log(c("yellow", "📝 Utente non trovato, creazione in corso..."));
98620
- const signupResult = await this.app.signup(username, password);
98621
- if (signupResult.success) {
98622
- // Aspetta un momento per evitare race condition
98623
- await new Promise((resolve) => setTimeout(resolve, 1000));
98624
- // Riprova login
98625
- result = await this.app.login(username, password);
98626
- }
98627
- else {
98628
- console.log(c("red", `❌ Signup fallito: ${signupResult.error}`));
98629
- return false;
98630
- }
98631
- }
98632
- if (result.success) {
98633
- this.currentUser = username;
98634
- this.derivedAddress = result.derivedAddress || "";
98635
- this.isAuthenticated = true;
98636
- console.log("");
98637
- console.log(c("green", "✅ Login effettuato!"));
98638
- console.log(c("gray", ` Username: ${c("bold", username)}`));
98639
- console.log(c("gray", ` Public Key: ${result.userPub?.substring(0, 40)}...`));
98640
- console.log(c("gray", ` Derived Address: ${c("cyan", result.derivedAddress || "")}`));
98641
- console.log("");
98642
- console.log(c("yellow", "📢 Pubblicazione chiave pubblica..."));
98643
- await this.app.publishPublicKey();
98644
- // Aspetta che la chiave sia sincronizzata
98645
- await new Promise((resolve) => setTimeout(resolve, 1000));
98646
- console.log(c("green", "✅ Chiave pubblicata su GunDB"));
98647
- console.log("");
98648
- // Ascolta messaggi
98649
- await this.app.listenForMessages((msg) => {
98650
- this.onMessageReceived(msg);
98651
- });
98652
- console.log(c("cyan", "💬 Chat pronta! Scrivi /help per i comandi disponibili"));
98653
- console.log("");
98654
- return true;
98655
- }
98656
- else {
98657
- console.log(c("red", `❌ Login fallito: ${result.error}`));
98658
- return false;
98659
- }
98660
- }
98661
- catch (error) {
98662
- clearInterval(loadingInterval);
98663
- console.log("");
98664
- console.log(c("red", `❌ Errore: ${error.message}`));
98665
- return false;
98666
- }
98667
- finally {
98668
- clearInterval(loadingInterval);
98669
- }
98670
- }
98671
- // ========================================================================
98672
- // MESSAGING
98673
- // ========================================================================
98674
- async sendMessage(content) {
98675
- if (!this.isAuthenticated) {
98676
- console.log(c("red", "❌ Non autenticato. Usa /login"));
98677
- return;
98678
- }
98679
- if (!this.recipient) {
98680
- console.log(c("yellow", "⚠️ Nessun destinatario. Usa /to <username>"));
98681
- return;
98682
- }
98683
- try {
98684
- const result = await this.app.sendMessage(this.recipient, content);
98685
- if (result.success) {
98686
- const time = new Date().toLocaleTimeString();
98687
- console.log(c("gray", `[${time}]`) +
98688
- " " +
98689
- c("green", `${this.currentUser}:`) +
98690
- " " +
98691
- content);
98692
- }
98693
- else {
98694
- console.log(c("red", `❌ Errore invio: ${result.error}`));
98695
- }
98696
- }
98697
- catch (error) {
98698
- console.log(c("red", `❌ Errore: ${error.message}`));
98699
- }
98700
- }
98701
- onMessageReceived(message) {
98702
- const time = new Date(message.timestamp).toLocaleTimeString();
98703
- const fromUser = message.from.substring(0, 10) + "...";
98704
- console.log("");
98705
- console.log(c("cyan", "📨 Nuovo messaggio!"));
98706
- console.log(c("gray", `[${time}]`) +
98707
- " " +
98708
- c("cyan", `${fromUser}:`) +
98709
- " " +
98710
- message.content);
98711
- console.log("");
98712
- this.rl.prompt();
98713
- }
98714
- // ========================================================================
98715
- // KEY PAIR MANAGEMENT
98716
- // ========================================================================
98717
- async exportKeyPair() {
98718
- try {
98719
- // Ottieni il SEA pair completo
98720
- const seaPair = this.app["shogun"].db.gun.user()?._?.sea;
98721
- if (!seaPair) {
98722
- console.log(c("red", "❌ Impossibile accedere al SEA pair"));
98723
- return;
98724
- }
98725
- // Crea export object
98726
- const exportData = {
98727
- pub: seaPair.pub,
98728
- priv: seaPair.priv,
98729
- epub: seaPair.epub,
98730
- epriv: seaPair.epriv,
98731
- alias: this.currentUser,
98732
- exportedAt: Date.now()
98733
- };
98734
- // Converti in base64 per facilità di copia
98735
- const jsonString = JSON.stringify(exportData);
98736
- const base64 = Buffer.from(jsonString).toString('base64');
98737
- console.log("");
98738
- console.log(c("green", "✅ KEY PAIR ESPORTATO"));
98739
- console.log(c("yellow", "═".repeat(60)));
98740
- console.log("");
98741
- console.log(c("bold", "🔑 SEA PAIR (Base64):"));
98742
- console.log("");
98743
- console.log(c("cyan", base64));
98744
- console.log("");
98745
- console.log(c("yellow", "═".repeat(60)));
98746
- console.log("");
98747
- console.log(c("gray", "💾 SALVA QUESTO KEY PAIR IN UN LUOGO SICURO!"));
98748
- console.log(c("gray", " Puoi usarlo per:"));
98749
- console.log(c("gray", " - Fare login: /login-pair <keypair>"));
98750
- console.log(c("gray", " - Importare: /import <keypair>"));
98751
- console.log(c("gray", " - Backup della tua identità"));
98752
- console.log("");
98753
- console.log(c("red", "⚠️ NON CONDIVIDERE MAI QUESTO KEY PAIR!"));
98754
- console.log(c("red", " Contiene le tue chiavi private!"));
98755
- console.log("");
98756
- // Salva anche su file (opzionale)
98757
- const fs = await __webpack_require__.e(/*! import() */ "_e6ae").then(__webpack_require__.t.bind(__webpack_require__, /*! fs */ "?e6ae", 23));
98758
- const filename = `shogun-keypair-${this.currentUser}-${Date.now()}.txt`;
98759
- fs.writeFileSync(filename, base64);
98760
- console.log(c("green", `💾 Key pair salvato anche in: ${filename}`));
98761
- console.log("");
98762
- }
98763
- catch (error) {
98764
- console.log(c("red", `❌ Errore export: ${error.message}`));
98765
- }
98766
- }
98767
- async importKeyPair(base64KeyPair) {
98768
- try {
98769
- // Decodifica da base64
98770
- const jsonString = Buffer.from(base64KeyPair, 'base64').toString('utf-8');
98771
- const keyPairData = JSON.parse(jsonString);
98772
- // Verifica che abbia tutti i campi necessari
98773
- if (!keyPairData.pub || !keyPairData.priv || !keyPairData.epub || !keyPairData.epriv) {
98774
- console.log(c("red", "❌ Key pair invalido. Mancano campi obbligatori."));
98775
- return;
98776
- }
98777
- console.log(c("cyan", "📥 Key pair importato con successo!"));
98778
- console.log(c("gray", ` Utente: ${keyPairData.alias || 'unknown'}`));
98779
- console.log(c("gray", ` Public Key: ${keyPairData.pub.substring(0, 30)}...`));
98780
- console.log("");
98781
- console.log(c("yellow", "💡 Usa /login-pair <keypair> per fare login"));
98782
- console.log("");
98783
- }
98784
- catch (error) {
98785
- console.log(c("red", `❌ Errore import: ${error.message}`));
98786
- console.log(c("gray", " Verifica che il key pair sia valido"));
98787
- }
98788
- }
98789
- async loginWithPair(base64KeyPair) {
98790
- console.log(c("cyan", "🔐 Login con key pair..."));
98791
- const loadingInterval = setInterval(() => {
98792
- process.stdout.write(c("gray", "."));
98793
- }, 500);
98794
- try {
98795
- // Decodifica key pair
98796
- const jsonString = Buffer.from(base64KeyPair, 'base64').toString('utf-8');
98797
- const keyPairData = JSON.parse(jsonString);
98798
- // Verifica validità
98799
- if (!keyPairData.pub || !keyPairData.priv || !keyPairData.epub || !keyPairData.epriv) {
98800
- throw new Error("Key pair invalido");
98801
- }
98802
- // Crea SEA pair object
98803
- const seaPair = {
98804
- pub: keyPairData.pub,
98805
- priv: keyPairData.priv,
98806
- epub: keyPairData.epub,
98807
- epriv: keyPairData.epriv
98808
- };
98809
- // Login con pair
98810
- const result = await this.withTimeout(this.app["shogun"].loginWithPair(seaPair), 15000, "Login timeout");
98811
- clearInterval(loadingInterval);
98812
- console.log("");
98813
- if (result.success) {
98814
- this.currentUser = keyPairData.alias || result.username || 'unknown';
98815
- this.derivedAddress = await this.app.deriveEthereumAddress(seaPair.pub);
98816
- this.isAuthenticated = true;
98817
- console.log("");
98818
- console.log(c("green", "✅ Login con key pair effettuato!"));
98819
- console.log(c("gray", ` Username: ${c("bold", this.currentUser)}`));
98820
- console.log(c("gray", ` Public Key: ${seaPair.pub.substring(0, 40)}...`));
98821
- console.log(c("gray", ` Derived Address: ${c("cyan", this.derivedAddress)}`));
98822
- console.log("");
98823
- console.log(c("yellow", "📢 Pubblicazione chiave pubblica..."));
98824
- await this.app.publishPublicKey();
98825
- await new Promise((resolve) => setTimeout(resolve, 1000));
98826
- console.log(c("green", "✅ Chiave pubblicata su GunDB"));
98827
- console.log("");
98828
- // Ascolta messaggi
98829
- await this.app.listenForMessages((msg) => {
98830
- this.onMessageReceived(msg);
98831
- });
98832
- console.log(c("cyan", "💬 Chat pronta!"));
98833
- console.log("");
98834
- this.updatePrompt();
98835
- }
98836
- else {
98837
- console.log(c("red", `❌ Login fallito: ${result.error}`));
98838
- }
98839
- }
98840
- catch (error) {
98841
- clearInterval(loadingInterval);
98842
- console.log("");
98843
- console.log(c("red", `❌ Errore: ${error.message}`));
98844
- }
98845
- finally {
98846
- clearInterval(loadingInterval);
98847
- }
98848
- }
98849
- async wipeAllMessages() {
98850
- console.log("");
98851
- console.log(c("yellow", "⚠️ ATTENZIONE: Stai per cancellare TUTTI i messaggi dal nodo GunDB"));
98852
- console.log(c("yellow", " Questa operazione è IRREVERSIBILE!"));
98853
- console.log("");
98854
- // Conferma
98855
- this.rl.question(c("red", "Sei sicuro? Scrivi 'CONFERMA' per procedere: "), (answer) => {
98856
- if (answer.trim() === "CONFERMA") {
98857
- console.log(c("yellow", "🗑️ Cancellazione messaggi in corso..."));
98858
- // Ottieni tutti i messaggi
98859
- this.app["shogun"].db.gun.get(SHIP_01_1.SHIP_01.NODES.MESSAGES).once((allMessages) => {
98860
- if (allMessages && typeof allMessages === 'object') {
98861
- let count = 0;
98862
- // Cancella ogni messaggio
98863
- for (const [messageId, data] of Object.entries(allMessages)) {
98864
- if (typeof data === "object" && data !== null && messageId !== '_') {
98865
- this.app["shogun"].db.gun.get(SHIP_01_1.SHIP_01.NODES.MESSAGES).get(messageId).put(null);
98866
- count++;
98867
- }
98868
- }
98869
- console.log(c("green", `✅ ${count} messaggi cancellati dal nodo GunDB`));
98870
- }
98871
- else {
98872
- console.log(c("gray", "ℹ️ Nessun messaggio da cancellare"));
98873
- }
98874
- console.log("");
98875
- this.rl.prompt();
98876
- });
98877
- }
98878
- else {
98879
- console.log(c("gray", "❌ Cancellazione annullata"));
98880
- console.log("");
98881
- this.rl.prompt();
98882
- }
98883
- });
98884
- }
98885
- // ========================================================================
98886
- // COMMANDS
98887
- // ========================================================================
98888
- async handleCommand(cmd) {
98889
- const parts = cmd.split(" ");
98890
- const command = parts[0].toLowerCase();
98891
- const args = parts.slice(1);
98892
- switch (command) {
98893
- case "/login":
98894
- if (args.length >= 2) {
98895
- const [username, password] = args;
98896
- await this.login(username, password);
98897
- this.updatePrompt();
98898
- }
98899
- else {
98900
- console.log(c("yellow", "⚠️ Uso: /login <username> <password>"));
98901
- }
98902
- break;
98903
- case "/to":
98904
- case "/chat":
98905
- if (!this.isAuthenticated) {
98906
- console.log(c("red", "❌ Prima fai login: /login <username> <password>"));
98907
- break;
98908
- }
98909
- if (args[0]) {
98910
- this.recipient = args[0];
98911
- console.log(c("cyan", `💬 Chattando con ${c("bold", this.recipient)}`));
98912
- // Carica storico
98913
- const history = await this.app.getMessageHistory(this.recipient);
98914
- if (history.length > 0) {
98915
- console.log(c("gray", `\n📚 Storico conversazione (${history.length} messaggi):\n`));
98916
- history.forEach((msg, i) => {
98917
- const time = new Date(msg.timestamp).toLocaleTimeString();
98918
- const isMe = msg.from === this.currentUser;
98919
- const from = isMe ? this.currentUser : this.recipient;
98920
- const color = isMe ? "green" : "cyan";
98921
- console.log(c("gray", `[${time}]`) +
98922
- " " +
98923
- c(color, `${from}:`) +
98924
- " " +
98925
- msg.content);
98926
- });
98927
- console.log("");
98928
- }
98929
- this.updatePrompt();
98930
- }
98931
- else {
98932
- console.log(c("yellow", "⚠️ Uso: /to <username>"));
98933
- }
98934
- break;
98935
- case "/help":
98936
- this.showHelp();
98937
- break;
98938
- case "/clear":
98939
- console.clear();
98940
- this.showHeader();
98941
- break;
98942
- case "/status":
98943
- this.showStatus();
98944
- break;
98945
- case "/logout":
98946
- this.app.logout();
98947
- this.isAuthenticated = false;
98948
- this.currentUser = "";
98949
- this.recipient = "";
98950
- console.log(c("yellow", "👋 Disconnesso"));
98951
- this.updatePrompt();
98952
- break;
98953
- case "/export":
98954
- case "/backup":
98955
- if (!this.isAuthenticated) {
98956
- console.log(c("red", "❌ Prima fai login"));
98957
- break;
98958
- }
98959
- await this.exportKeyPair();
98960
- break;
98961
- case "/import":
98962
- case "/restore":
98963
- if (args[0]) {
98964
- await this.importKeyPair(args[0]);
98965
- }
98966
- else {
98967
- console.log(c("yellow", "⚠️ Uso: /import <keypair-json-base64>"));
98968
- }
98969
- break;
98970
- case "/login-pair":
98971
- if (args[0]) {
98972
- await this.loginWithPair(args[0]);
98973
- }
98974
- else {
98975
- console.log(c("yellow", "⚠️ Uso: /login-pair <keypair-json-base64>"));
98976
- }
98977
- break;
98978
- case "/wipe":
98979
- case "/delete-all":
98980
- if (!this.isAuthenticated) {
98981
- console.log(c("red", "❌ Prima fai login"));
98982
- break;
98983
- }
98984
- await this.wipeAllMessages();
98985
- break;
98986
- case "/exit":
98987
- case "/quit":
98988
- this.rl.close();
98989
- break;
98990
- default:
98991
- console.log(c("red", `❌ Comando sconosciuto: ${command}`));
98992
- console.log(c("gray", " Scrivi /help per aiuto"));
98993
- }
98994
- }
98995
- showHelp() {
98996
- console.log("");
98997
- console.log(c("bold", c("cyan", "📖 COMANDI DISPONIBILI")));
98998
- console.log("");
98999
- console.log(c("bold", "AUTENTICAZIONE:"));
99000
- console.log(" " + c("bold", "/login <user> <pass>") + " - Login/Signup con password");
99001
- console.log(" " + c("bold", "/login-pair <keypair>") + " - Login con SEA key pair");
99002
- console.log("");
99003
- console.log(c("bold", "MESSAGGISTICA:"));
99004
- console.log(" " + c("bold", "/to <username>") + " - Inizia chat con un utente");
99005
- console.log("");
99006
- console.log(c("bold", "KEY MANAGEMENT:"));
99007
- console.log(" " + c("bold", "/export") + " - Esporta il tuo key pair (backup)");
99008
- console.log(" " + c("bold", "/import <keypair>") + " - Mostra info su key pair");
99009
- console.log("");
99010
- console.log(c("bold", "UTILITÀ:"));
99011
- console.log(" " + c("bold", "/help") + " - Mostra questo aiuto");
99012
- console.log(" " + c("bold", "/status") + " - Mostra stato connessione");
99013
- console.log(" " + c("bold", "/clear") + " - Pulisci schermo");
99014
- console.log(" " + c("bold", "/wipe") + " - Cancella TUTTI i messaggi (⚠️)");
99015
- console.log(" " + c("bold", "/logout") + " - Disconnetti");
99016
- console.log(" " + c("bold", "/exit") + " - Esci dall'app");
99017
- console.log("");
99018
- console.log(c("bold", c("green", "🔐 SICUREZZA")));
99019
- console.log("");
99020
- console.log(" ✅ Crittografia end-to-end (ECDH + AES-GCM)");
99021
- console.log(" ✅ Storage decentralizzato P2P (GunDB)");
99022
- console.log(" ✅ Nessun server può leggere i messaggi");
99023
- console.log(" ✅ Key pair portabile (export/import)");
99024
- console.log(" ✅ Zero costi, completamente gratis");
99025
- console.log("");
99026
- console.log(c("bold", c("yellow", "💡 ESEMPI")));
99027
- console.log("");
99028
- console.log(" " + c("gray", "# Login normale"));
99029
- console.log(" " + c("gray", "/login alice password123"));
99030
- console.log("");
99031
- console.log(" " + c("gray", "# Export key pair (backup)"));
99032
- console.log(" " + c("gray", "/export"));
99033
- console.log("");
99034
- console.log(" " + c("gray", "# Login con key pair (no password)"));
99035
- console.log(" " + c("gray", "/login-pair eyJwdWIiOiIuLi4ifQ=="));
99036
- console.log("");
99037
- console.log(" " + c("gray", "# Chattare"));
99038
- console.log(" " + c("gray", "/to bob"));
99039
- console.log(" " + c("gray", "Ciao Bob! Come stai?"));
99040
- console.log("");
99041
- }
99042
- showStatus() {
99043
- console.log("");
99044
- console.log(c("bold", c("cyan", "📊 STATO SISTEMA")));
99045
- console.log("");
99046
- console.log(" " + c("gray", "Utente:") + " " + c("green", this.currentUser));
99047
- console.log(" " +
99048
- c("gray", "Destinatario:") +
99049
- " " +
99050
- c("yellow", this.recipient || "(nessuno)"));
99051
- console.log(" " + c("gray", "Address:") + " " + c("cyan", this.derivedAddress));
99052
- console.log(" " +
99053
- c("gray", "Autenticato:") +
99054
- " " +
99055
- (this.isAuthenticated ? c("green", "✅ Sì") : c("red", "❌ No")));
99056
- console.log("");
99057
- }
99058
- showHeader() {
99059
- console.log("");
99060
- console.log(c("bold", c("cyan", "═══════════════════════════════════════════════════════")));
99061
- console.log(c("bold", c("cyan", " 🗡️ SHOGUN CHAT - Decentralized E2E Messaging")));
99062
- console.log(c("bold", c("cyan", "═══════════════════════════════════════════════════════")));
99063
- console.log("");
99064
- console.log(c("gray", " Powered by Shogun Core + GunDB"));
99065
- console.log(c("gray", " Zero-cost encrypted messaging over P2P network"));
99066
- console.log("");
99067
- }
99068
- updatePrompt() {
99069
- let prompt = "";
99070
- if (this.recipient) {
99071
- prompt =
99072
- c("green", `[${this.currentUser}]`) +
99073
- c("white", " → ") +
99074
- c("yellow", this.recipient) +
99075
- c("green", " ➤ ");
99076
- }
99077
- else if (this.currentUser) {
99078
- prompt = c("green", `[${this.currentUser}]`) + c("green", " ➤ ");
99079
- }
99080
- else {
99081
- prompt = c("gray", "➤ ");
99082
- }
99083
- this.rl.setPrompt(prompt);
99084
- }
99085
- // ========================================================================
99086
- // START
99087
- // ========================================================================
99088
- async start() {
99089
- this.showHeader();
99090
- const args = process.argv.slice(2);
99091
- if (args.length >= 2) {
99092
- // Auto-login
99093
- const [username, password] = args;
99094
- const success = await this.login(username, password);
99095
- if (success) {
99096
- this.updatePrompt();
99097
- this.rl.prompt();
99098
- }
99099
- else {
99100
- console.log(c("red", "❌ Auto-login fallito"));
99101
- this.rl.close();
99102
- }
99103
- }
99104
- else {
99105
- // Login manuale
99106
- console.log(c("cyan", "💡 Comandi disponibili:"));
99107
- console.log(c("yellow", " /login <username> <password>") +
99108
- c("gray", " - Login o crea account"));
99109
- console.log(c("yellow", " /help") +
99110
- c("gray", " - Mostra tutti i comandi"));
99111
- console.log("");
99112
- console.log(c("gray", " Oppure avvia con: yarn chat <username> <password>"));
99113
- console.log("");
99114
- this.updatePrompt();
99115
- this.rl.prompt();
99116
- }
99117
- }
99118
- }
99119
- exports.MessengerCLI = MessengerCLI;
99120
- // ============================================================================
99121
- // MAIN
99122
- // ============================================================================
99123
- const cli = new MessengerCLI();
99124
- cli.start().catch(console.error);
99125
-
99126
-
99127
- /***/ }),
99128
-
99129
- /***/ "./ship/implementation/SHIP_01.ts":
99130
- /*!****************************************!*\
99131
- !*** ./ship/implementation/SHIP_01.ts ***!
99132
- \****************************************/
99133
- /***/ (function(module, exports, __webpack_require__) {
99134
-
99135
- "use strict";
99136
- /* module decorator */ module = __webpack_require__.nmd(module);
99137
-
99138
- /**
99139
- * Esempio Pratico: Messaggistica Decentralizzata con Shogun Core
99140
- *
99141
- * Questo esempio mostra come creare un sistema di messaggistica sicuro usando:
99142
- * - Shogun Core per autenticazione (username/password)
99143
- * - GunDB per storage decentralizzato P2P
99144
- * - SEA (Security, Encryption, Authorization) per crittografia
99145
- *
99146
- * Vantaggi:
99147
- * ✅ Completamente decentralizzato (no server centrale)
99148
- * ✅ Zero costi (no blockchain, no gas fees)
99149
- * ✅ Real-time messaging
99150
- * ✅ Offline-first
99151
- * ✅ End-to-end encryption
99152
- *
99153
- * Note sull'ERC7627:
99154
- * L'EIP era un template concettuale. Questo esempio implementa
99155
- * solo la parte GunDB/Shogun Core senza interazione blockchain.
99156
- * La funzione deriveEthereumAddress() rimane come utility per derivare
99157
- * un address Ethereum dalla chiave GunDB se necessario in futuro.
99158
- */
99159
- var __importDefault = (this && this.__importDefault) || function (mod) {
99160
- return (mod && mod.__esModule) ? mod : { "default": mod };
99161
- };
99162
- Object.defineProperty(exports, "__esModule", ({ value: true }));
99163
- exports.SHIP_01 = void 0;
99164
- const core_1 = __webpack_require__(/*! ../../src/core */ "./src/core.ts");
99165
- const ethers_1 = __webpack_require__(/*! ethers */ "./node_modules/ethers/lib.commonjs/index.js");
99166
- const derive_1 = __importDefault(__webpack_require__(/*! ../../src/gundb/derive */ "./src/gundb/derive.ts"));
99167
- // ============================================================================
99168
- // 1. SETUP: Inizializzazione del Sistema Completo
99169
- // ============================================================================
99170
- /**
99171
- * Classe per messaggistica sicura con Shogun Core
99172
- * Implementa l'interfaccia ISHIP_01
99173
- * Usa solo GunDB per storage decentralizzato (no blockchain)
99174
- */
99175
- class SHIP_01 {
99176
- constructor(shogunConfig) {
99177
- // Inizializza Shogun Core
99178
- this.shogun = new core_1.ShogunCore(shogunConfig);
99179
- }
99180
- // ========================================================================
99181
- // 2. AUTENTICAZIONE: Username e Password
99182
- // ========================================================================
99183
- /**
99184
- * Registra un nuovo utente
99185
- */
99186
- async signup(username, password) {
99187
- try {
99188
- // Registra con Shogun Core (crea SEA pair automaticamente)
99189
- const signupResult = await this.shogun.signUp(username, password);
99190
- if (!signupResult.success) {
99191
- return {
99192
- success: false,
99193
- error: signupResult.error || "Signup failed",
99194
- };
99195
- }
99196
- console.log("✅ Utente registrato");
99197
- console.log(` Username: ${username}`);
99198
- console.log(` GunDB Public Key: ${signupResult.pub}`);
99199
- // Opzionale: deriva address Ethereum dalla chiave GunDB
99200
- const derivedAddress = signupResult.pub
99201
- ? await this.deriveEthereumAddress(signupResult.pub)
99202
- : undefined;
99203
- if (derivedAddress) {
99204
- console.log(` Derived Address: ${derivedAddress}`);
99205
- }
99206
- return {
99207
- success: true,
99208
- userPub: signupResult.pub,
99209
- derivedAddress,
99210
- };
99211
- }
99212
- catch (error) {
99213
- return {
99214
- success: false,
99215
- error: error.message,
99216
- };
99217
- }
99218
- }
99219
- /**
99220
- * Login con username e password
99221
- */
99222
- async login(username, password) {
99223
- try {
99224
- // Login con Shogun Core
99225
- const loginResult = await this.shogun.login(username, password);
99226
- if (!loginResult.success) {
99227
- return {
99228
- success: false,
99229
- error: loginResult.error || "Login failed",
99230
- };
99231
- }
99232
- console.log("✅ Login effettuato");
99233
- console.log(` Username: ${username}`);
99234
- console.log(` GunDB Public Key: ${loginResult.userPub}`);
99235
- // Opzionale: deriva address Ethereum dalla chiave GunDB
99236
- const derivedAddress = loginResult.userPub
99237
- ? await this.deriveEthereumAddress(loginResult.userPub)
99238
- : undefined;
99239
- if (derivedAddress) {
99240
- console.log(` Derived Address: ${derivedAddress}`);
99241
- }
99242
- return {
99243
- success: true,
99244
- userPub: loginResult.userPub,
99245
- derivedAddress,
99246
- };
99247
- }
99248
- catch (error) {
99249
- return {
99250
- success: false,
99251
- error: error.message,
99252
- };
99253
- }
99254
- }
99255
- /**
99256
- * Login con SEA Key Pair
99257
- *
99258
- * Autenticazione diretta usando un key pair esportato.
99259
- * Utile per:
99260
- * - Recupero account senza password
99261
- * - Portabilità tra dispositivi
99262
- * - Backup dell'identità
99263
- */
99264
- async loginWithPair(seaPair) {
99265
- try {
99266
- console.log("🔐 Login con key pair...");
99267
- // Autentica con GunDB usando il pair
99268
- const authResult = await new Promise((resolve) => {
99269
- this.shogun.db.gun.user().auth(seaPair, (ack) => {
99270
- if (ack.err) {
99271
- resolve({
99272
- success: false,
99273
- error: ack.err,
99274
- });
99275
- }
99276
- else {
99277
- resolve({
99278
- success: true,
99279
- userPub: seaPair.pub,
99280
- });
99281
- }
99282
- });
99283
- });
99284
- if (!authResult.success) {
99285
- console.log("❌ Login fallito:", authResult.error);
99286
- return authResult;
99287
- }
99288
- // Opzionale: deriva address Ethereum dalla chiave GunDB
99289
- const derivedAddress = await this.deriveEthereumAddress(seaPair.pub);
99290
- console.log("✅ Login effettuato");
99291
- console.log(` GunDB Public Key: ${seaPair.pub}`);
99292
- console.log(` Derived Address: ${derivedAddress}`);
99293
- return {
99294
- success: true,
99295
- userPub: authResult.userPub,
99296
- derivedAddress,
99297
- };
99298
- }
99299
- catch (error) {
99300
- console.error("❌ Errore login con pair:", error);
99301
- return {
99302
- success: false,
99303
- error: error instanceof Error ? error.message : "Unknown error",
99304
- };
99305
- }
99306
- }
99307
- /**
99308
- * Logout
99309
- */
99310
- logout() {
99311
- this.shogun.logout();
99312
- console.log("👋 Logout effettuato");
99313
- }
99314
- /**
99315
- * Verifica se l'utente è autenticato
99316
- */
99317
- isLoggedIn() {
99318
- return this.shogun.isLoggedIn();
99319
- }
99320
- // ========================================================================
99321
- // 3. GESTIONE CHIAVI PUBBLICHE: Salva su GunDB
99322
- // ========================================================================
99323
- /**
99324
- * Salva la chiave pubblica dell'utente su GunDB
99325
- * Questo permette ad altri di trovare la tua chiave per criptare messaggi
99326
- */
99327
- async publishPublicKey() {
99328
- try {
99329
- if (!this.isLoggedIn()) {
99330
- return { success: false, error: "Not logged in" };
99331
- }
99332
- // Ottieni il SEA pair dell'utente corrente
99333
- const currentUser = this.shogun.db.user;
99334
- if (!currentUser || !currentUser.is) {
99335
- return { success: false, error: "No user session" };
99336
- }
99337
- // Salva chiave pubblica sul nodo globale usando il userPub come chiave
99338
- // Questo permette ad altri di trovarla facilmente
99339
- const userPub = currentUser.is.pub;
99340
- await this.shogun.db.gun
99341
- .get(userPub)
99342
- .put({
99343
- pub: currentUser.is.pub,
99344
- epub: currentUser.is.epub,
99345
- algorithm: "ECDSA",
99346
- timestamp: Date.now().toString(),
99347
- })
99348
- .then();
99349
- console.log(`📝 Chiave pubblica pubblicata su GunDB`);
99350
- return { success: true };
99351
- }
99352
- catch (error) {
99353
- console.error("❌ Errore pubblicazione chiave:", error);
99354
- return { success: false, error: error.message };
99355
- }
99356
- }
99357
- // ========================================================================
99358
- // 4. INVIO MESSAGGI: Solo GunDB
99359
- // ========================================================================
99360
- /**
99361
- * Invia un messaggio crittografato a un altro utente
99362
- */
99363
- async sendMessage(recipientUsername, message) {
99364
- try {
99365
- if (!this.isLoggedIn()) {
99366
- return { success: false, error: "Not logged in" };
99367
- }
99368
- const currentUser = this.shogun.db.user;
99369
- if (!currentUser || !currentUser.is) {
99370
- return { success: false, error: "No user session" };
99371
- }
99372
- // 1. Ottieni la chiave pubblica del destinatario
99373
- const recipientKey = await this.getRecipientPublicKey(recipientUsername);
99374
- if (!recipientKey) {
99375
- return {
99376
- success: false,
99377
- error: `Recipient ${recipientUsername} has not published their public key`,
99378
- };
99379
- }
99380
- // 2. Ottieni il SEA pair completo (include chiavi private)
99381
- const senderPair = this.shogun.db.gun.user()?._?.sea;
99382
- if (!senderPair) {
99383
- return { success: false, error: "Cannot access SEA pair" };
99384
- }
99385
- // 3. Cripta il messaggio usando SEA.secret + SEA.encrypt (ECDH)
99386
- const encryptedMessage = await this.shogun.db.crypto.encFor(message, senderPair, // sender pair completo
99387
- { epub: recipientKey.epub } // recipient public encryption key
99388
- );
99389
- // 4. Genera ID messaggio
99390
- const messageId = this.generateMessageId();
99391
- const senderPub = currentUser.is.pub;
99392
- // 5. Salva messaggio crittografato su GunDB
99393
- const messageData = {
99394
- from: senderPub,
99395
- to: recipientUsername,
99396
- content: encryptedMessage, // Contenuto crittografato!
99397
- timestamp: Date.now().toString(),
99398
- messageId: messageId,
99399
- };
99400
- // Salva sul nodo globale 'messages' per permettere il listener
99401
- await this.shogun.db.gun
99402
- .get(SHIP_01.NODES.MESSAGES)
99403
- .get(messageId)
99404
- .put(messageData)
99405
- .then();
99406
- console.log(`✅ Messaggio salvato: ${messageId}`);
99407
- return {
99408
- success: true,
99409
- messageId: messageId,
99410
- };
99411
- }
99412
- catch (error) {
99413
- return {
99414
- success: false,
99415
- error: error.message,
99416
- };
99417
- }
99418
- }
99419
- /**
99420
- * Ottiene la chiave pubblica di un utente da GunDB
99421
- */
99422
- async getRecipientPublicKey(username) {
99423
- try {
99424
- // Prima trova l'utente dal username
99425
- const userData = await this.shogun.db.getUserByAlias(username);
99426
- if (!userData || !userData.userPub) {
99427
- console.error(`❌ User ${username} not found`);
99428
- return null;
99429
- }
99430
- const userPub = userData.userPub;
99431
- // Le chiavi sono salvate direttamente sul nodo userPub
99432
- const publicKeyData = await this.shogun.db.gun.get(userPub).then();
99433
- if (publicKeyData && publicKeyData.epub && publicKeyData.pub) {
99434
- return {
99435
- pub: publicKeyData.pub,
99436
- epub: publicKeyData.epub,
99437
- };
99438
- }
99439
- return null;
99440
- }
99441
- catch (error) {
99442
- console.error("❌ Errore recupero chiave pubblica:", error);
99443
- return null;
99444
- }
99445
- }
99446
- // ========================================================================
99447
- // 5. RICEZIONE MESSAGGI: Ascolta GunDB in real-time
99448
- // ========================================================================
99449
- /**
99450
- * Ascolta messaggi crittografati in arrivo su GunDB
99451
- */
99452
- async listenForMessages(onMessage) {
99453
- if (!this.isLoggedIn()) {
99454
- console.error("❌ Non autenticato");
99455
- return;
99456
- }
99457
- const currentUser = this.shogun.db.user;
99458
- if (!currentUser || !currentUser.is) {
99459
- console.error("❌ Nessuna sessione utente");
99460
- return;
99461
- }
99462
- const userPub = currentUser.is.pub;
99463
- // Ottieni username dell'utente corrente
99464
- const username = currentUser.is.alias;
99465
- // Set per tracciare messaggi già ricevuti (evita duplicati)
99466
- const receivedMessages = new Set();
99467
- // Ascolta messaggi in tempo reale su GunDB
99468
- this.shogun.db.gun
99469
- .get(SHIP_01.NODES.MESSAGES)
99470
- .map()
99471
- .on(async (data, key) => {
99472
- // Filtra solo i messaggi destinati a questo utente (per username)
99473
- if (data &&
99474
- data.to === username &&
99475
- data.from &&
99476
- data.content &&
99477
- data.messageId) {
99478
- // Evita duplicati (GunDB può emettere più volte)
99479
- if (receivedMessages.has(data.messageId)) {
99480
- return;
99481
- }
99482
- receivedMessages.add(data.messageId);
99483
- try {
99484
- // Decripta il messaggio
99485
- const decryptedContent = await this.decryptMessage(data.content, data.from);
99486
- onMessage({
99487
- from: data.from,
99488
- content: decryptedContent,
99489
- timestamp: parseInt(data.timestamp),
99490
- });
99491
- }
99492
- catch (error) {
99493
- console.error("❌ Errore decrittazione messaggio:", error);
99494
- }
99495
- }
99496
- });
99497
- console.log(`👂 In ascolto di messaggi per ${username} (${userPub.substring(0, 10)}...)`);
99498
- }
99499
- /**
99500
- * Decripta un messaggio usando SEA.secret + SEA.decrypt (ECDH)
99501
- */
99502
- async decryptMessage(encryptedContent, senderPub) {
99503
- // Ottieni il SEA pair completo del destinatario (noi)
99504
- const receiverPair = this.shogun.db.gun.user()?._?.sea;
99505
- if (!receiverPair) {
99506
- throw new Error("Cannot access SEA pair");
99507
- }
99508
- // Ottieni epub del mittente
99509
- const senderKey = await this.getPublicKeyByPub(senderPub);
99510
- if (!senderKey) {
99511
- throw new Error("Sender public key not found");
99512
- }
99513
- // Decripta usando SEA.secret + SEA.decrypt (ECDH)
99514
- const decrypted = await this.shogun.db.crypto.decFrom(encryptedContent, { epub: senderKey.epub }, // sender's public encryption key
99515
- receiverPair // receiver's pair completo
99516
- );
99517
- return decrypted;
99518
- }
99519
- /**
99520
- * Ottiene la chiave pubblica di un utente dalla sua pub key
99521
- */
99522
- async getPublicKeyByPub(userPub) {
99523
- try {
99524
- // Le chiavi sono salvate direttamente sul nodo userPub
99525
- const publicKeyData = await this.shogun.db.gun.get(userPub).then();
99526
- if (publicKeyData && publicKeyData.epub && publicKeyData.pub) {
99527
- return {
99528
- pub: publicKeyData.pub,
99529
- epub: publicKeyData.epub,
99530
- };
99531
- }
99532
- return null;
99533
- }
99534
- catch (error) {
99535
- console.error("❌ Errore recupero chiave:", error);
99536
- return null;
99537
- }
99538
- }
99539
- // ========================================================================
99540
- // 6. RECUPERO STORICO: Query messaggi passati
99541
- // ========================================================================
99542
- /**
99543
- * Recupera lo storico dei messaggi crittografati con un utente
99544
- */
99545
- async getMessageHistory(withUsername) {
99546
- if (!this.isLoggedIn()) {
99547
- console.error("❌ Non autenticato");
99548
- return [];
99549
- }
99550
- const currentUser = this.shogun.db.user;
99551
- if (!currentUser || !currentUser.is) {
99552
- console.error("❌ Nessuna sessione utente");
99553
- return [];
99554
- }
99555
- const userPub = currentUser.is.pub;
99556
- const username = currentUser.is.alias;
99557
- const allMessages = [];
99558
- // Ottieni il userPub dell'altro utente
99559
- const otherUserData = await this.shogun.db.getUserByAlias(withUsername);
99560
- const otherUserPub = otherUserData?.userPub;
99561
- // Use .map() instead of .then() to iterate all messages
99562
- return new Promise((resolve) => {
99563
- const messages = [];
99564
- let messageCount = 0;
99565
- this.shogun.db.gun
99566
- .get(SHIP_01.NODES.MESSAGES)
99567
- .map()
99568
- .once(async (msgData, messageId) => {
99569
- // Skip metadata fields
99570
- if (!msgData || typeof msgData !== "object" || messageId === "_") {
99571
- return;
99572
- }
99573
- messageCount++;
99574
- try {
99575
- // Check if message is part of this conversation
99576
- // Fixed: Handle both username and userPub in matching
99577
- const isSentToTarget = msgData.from === userPub &&
99578
- (msgData.to === withUsername || msgData.to === otherUserPub);
99579
- const isReceivedFromTarget = (msgData.to === username || msgData.to === userPub) &&
99580
- msgData.from === otherUserPub;
99581
- if (isSentToTarget || isReceivedFromTarget) {
99582
- // Decrypt message
99583
- const decryptedContent = await this.decryptMessage(msgData.content, msgData.from);
99584
- messages.push({
99585
- from: msgData.from,
99586
- to: msgData.to,
99587
- content: decryptedContent,
99588
- timestamp: parseInt(msgData.timestamp),
99589
- });
99590
- }
99591
- }
99592
- catch (error) {
99593
- // Silent error - message couldn't be decrypted
99594
- }
99595
- });
99596
- // Wait a bit for GunDB to return all messages, then resolve
99597
- setTimeout(() => {
99598
- const sorted = messages.sort((a, b) => a.timestamp - b.timestamp);
99599
- resolve(sorted);
99600
- }, 2000);
99601
- });
99602
- }
99603
- // ========================================================================
99604
- // 7. UTILITY FUNCTIONS
99605
- // ========================================================================
99606
- /**
99607
- * Converte la chiave pubblica di GunDB in address Ethereum
99608
- * Usa la chiave privata SEA come seed per derivazione deterministica
99609
- *
99610
- * Questo garantisce che:
99611
- * - Stesso SEA pair → stesso address Ethereum
99612
- * - Derivazione cryptografica sicura
99613
- * - Identità unificata tra GunDB e blockchain
99614
- */
99615
- async deriveEthereumAddress(publicKey) {
99616
- try {
99617
- // Ottieni il SEA pair completo
99618
- const seaPair = this.shogun.db.gun.user()?._?.sea;
99619
- if (!seaPair || !seaPair.priv) {
99620
- throw new Error("Cannot access SEA pair");
99621
- }
99622
- // Usa la chiave privata SEA come seed per derive
99623
- // Questo è MOLTO più sicuro e deterministico del username!
99624
- const derived = await (0, derive_1.default)(seaPair.priv, null, {
99625
- includeSecp256k1Ethereum: true,
99626
- includeP256: false,
99627
- includeSecp256k1Bitcoin: false,
99628
- });
99629
- return derived.secp256k1Ethereum.address;
99630
- }
99631
- catch (error) {
99632
- console.error("❌ Errore derivazione address:", error);
99633
- // Fallback: hash della chiave pubblica
99634
- const fallbackKey = publicKey || "unknown";
99635
- const hash = ethers_1.ethers.keccak256(ethers_1.ethers.toUtf8Bytes(fallbackKey));
99636
- return ethers_1.ethers.getAddress("0x" + hash.slice(-40));
99637
- }
99638
- }
99639
- /**
99640
- * Genera ID messaggio univoco
99641
- */
99642
- generateMessageId() {
99643
- return ethers_1.ethers.hexlify(ethers_1.ethers.randomBytes(16));
99644
- }
99645
- }
99646
- exports.SHIP_01 = SHIP_01;
99647
- // GunDB Node Names - Constants for clarity
99648
- SHIP_01.NODES = {
99649
- MESSAGES: "messages",
99650
- USERS: "users",
99651
- PUBLIC_KEYS: "publicKeys",
99652
- };
99653
- async function testAliceAndBob() {
99654
- console.log("🧪 TEST: Alice e Bob - Conversazione Crittografata E2E\n");
99655
- console.log("=".repeat(60));
99656
- // Setup Alice
99657
- console.log("\n👩 ALICE - Setup");
99658
- console.log("-".repeat(60));
99659
- const alice = new SHIP_01({
99660
- gunOptions: {
99661
- peers: ["https://peer.wallie.io/gun"],
99662
- radisk: true,
99663
- },
99664
- });
99665
- // Alice signup/login
99666
- await alice.signup("alice", "password123");
99667
- const aliceLogin = await alice.login("alice", "password123");
99668
- if (!aliceLogin.success) {
99669
- console.error("❌ Alice login failed");
99670
- return;
99671
- }
99672
- await alice.publishPublicKey();
99673
- // Aspetta che la chiave sia sincronizzata
99674
- await new Promise((resolve) => setTimeout(resolve, 1000));
99675
- // Setup Bob
99676
- console.log("\n👨 BOB - Setup");
99677
- console.log("-".repeat(60));
99678
- const bob = new SHIP_01({
99679
- gunOptions: {
99680
- peers: ["https://peer.wallie.io/gun"],
99681
- radisk: true,
99682
- },
99683
- });
99684
- // Bob signup/login
99685
- await bob.signup("bob", "password456");
99686
- const bobLogin = await bob.login("bob", "password456");
99687
- if (!bobLogin.success) {
99688
- console.error("❌ Bob login failed");
99689
- return;
99690
- }
99691
- await bob.publishPublicKey();
99692
- // Aspetta che la chiave sia sincronizzata
99693
- await new Promise((resolve) => setTimeout(resolve, 1000));
99694
- console.log("\n" + "=".repeat(60));
99695
- console.log("💬 CONVERSAZIONE");
99696
- console.log("=".repeat(60));
99697
- // Alice e Bob ascoltano messaggi
99698
- let aliceMessages = [];
99699
- let bobMessages = [];
99700
- await alice.listenForMessages((msg) => {
99701
- aliceMessages.push(msg);
99702
- console.log(`\n[Alice riceve] 📨`);
99703
- console.log(` Da: ${msg.from.substring(0, 10)}...`);
99704
- console.log(` Messaggio: "${msg.content}"`);
99705
- console.log(` Timestamp: ${new Date(msg.timestamp).toLocaleTimeString()}`);
99706
- });
99707
- await bob.listenForMessages((msg) => {
99708
- bobMessages.push(msg);
99709
- console.log(`\n[Bob riceve] 📨`);
99710
- console.log(` Da: ${msg.from.substring(0, 10)}...`);
99711
- console.log(` Messaggio: "${msg.content}"`);
99712
- console.log(` Timestamp: ${new Date(msg.timestamp).toLocaleTimeString()}`);
99713
- });
99714
- // Aspetta che i listener siano pronti
99715
- await new Promise((resolve) => setTimeout(resolve, 2000));
99716
- // Alice invia messaggio a Bob
99717
- console.log("\n[Alice invia] 📤");
99718
- const msg1 = await alice.sendMessage("bob", "Ciao Bob! Come stai? 👋");
99719
- console.log(` ✅ Inviato: "${msg1.messageId}"`);
99720
- // Aspetta che Bob riceva
99721
- await new Promise((resolve) => setTimeout(resolve, 2000));
99722
- // Bob risponde ad Alice
99723
- console.log("\n[Bob invia] 📤");
99724
- const msg2 = await bob.sendMessage("alice", "Ciao Alice! Tutto bene, grazie! Tu? 😊");
99725
- console.log(` ✅ Inviato: "${msg2.messageId}"`);
99726
- // Aspetta che Alice riceva
99727
- await new Promise((resolve) => setTimeout(resolve, 2000));
99728
- // Alice risponde
99729
- console.log("\n[Alice invia] 📤");
99730
- const msg3 = await alice.sendMessage("bob", "Anch'io benissimo! Questo sistema di messaggistica è fantastico! 🚀");
99731
- console.log(` ✅ Inviato: "${msg3.messageId}"`);
99732
- // Aspetta che Bob riceva
99733
- await new Promise((resolve) => setTimeout(resolve, 2000));
99734
- // Bob conclude
99735
- console.log("\n[Bob invia] 📤");
99736
- const msg4 = await bob.sendMessage("alice", "Vero! Zero costi, decentralizzato e veloce! 💪");
99737
- console.log(` ✅ Inviato: "${msg4.messageId}"`);
99738
- // Aspetta finale
99739
- await new Promise((resolve) => setTimeout(resolve, 3000));
99740
- // Mostra statistiche
99741
- console.log("\n" + "=".repeat(60));
99742
- console.log("📊 STATISTICHE FINALI");
99743
- console.log("=".repeat(60));
99744
- console.log(`\n👩 Alice:`);
99745
- console.log(` - Messaggi inviati: 2`);
99746
- console.log(` - Messaggi ricevuti: ${aliceMessages.length}`);
99747
- console.log(` - Public Key: ${aliceLogin.userPub?.substring(0, 20)}...`);
99748
- console.log(` - Derived Address: ${aliceLogin.derivedAddress}`);
99749
- console.log(`\n👨 Bob:`);
99750
- console.log(` - Messaggi inviati: 2`);
99751
- console.log(` - Messaggi ricevuti: ${bobMessages.length}`);
99752
- console.log(` - Public Key: ${bobLogin.userPub?.substring(0, 20)}...`);
99753
- console.log(` - Derived Address: ${bobLogin.derivedAddress}`);
99754
- // Recupera storico
99755
- console.log("\n" + "=".repeat(60));
99756
- console.log("📚 STORICO CONVERSAZIONE");
99757
- console.log("=".repeat(60));
99758
- const aliceHistory = await alice.getMessageHistory("bob");
99759
- console.log(`\n👩 Storico di Alice con Bob (${aliceHistory.length} messaggi):`);
99760
- aliceHistory.forEach((msg, i) => {
99761
- const sender = msg.from === aliceLogin.userPub ? "Alice" : "Bob";
99762
- console.log(` ${i + 1}. [${sender}]: ${msg.content}`);
99763
- });
99764
- const bobHistory = await bob.getMessageHistory("alice");
99765
- console.log(`\n👨 Storico di Bob con Alice (${bobHistory.length} messaggi):`);
99766
- bobHistory.forEach((msg, i) => {
99767
- const sender = msg.from === bobLogin.userPub ? "Bob" : "Alice";
99768
- console.log(` ${i + 1}. [${sender}]: ${msg.content}`);
99769
- });
99770
- // Riepilogo finale
99771
- console.log("\n" + "=".repeat(60));
99772
- console.log("✅ TEST COMPLETATO CON SUCCESSO!");
99773
- console.log("=".repeat(60));
99774
- console.log("\n📝 Riepilogo:");
99775
- console.log(" ✅ 2 utenti registrati (Alice, Bob)");
99776
- console.log(" ✅ 4 messaggi scambiati");
99777
- console.log(" ✅ Messaggi ricevuti in real-time");
99778
- console.log(" ✅ Storico recuperato correttamente");
99779
- console.log(" ✅ Storage: GunDB P2P (gratis!)");
99780
- console.log(" ✅ Costi: $0.00");
99781
- console.log("\n🎉 Sistema di messaggistica decentralizzato funzionante!\n");
99782
- }
99783
- // Esegui esempio o test
99784
- if (__webpack_require__.c[__webpack_require__.s] === module) {
99785
- testAliceAndBob().catch(console.error); // Test completo Alice & Bob
99786
- }
99787
-
99788
-
99789
99032
  /***/ }),
99790
99033
 
99791
99034
  /***/ "./src/config/simplified-config.ts":
@@ -101524,11 +100767,16 @@ const CONFIG = {
101524
100767
  },
101525
100768
  };
101526
100769
  class DataBase {
101527
- constructor(gun, appScope = "shogun") {
100770
+ constructor(gun, appScope = "shogun", options) {
101528
100771
  this.user = null;
101529
100772
  this.onAuthCallbacks = [];
100773
+ this.disableAutoRecall = false;
100774
+ this.silent = false;
101530
100775
  // Initialize event emitter
101531
100776
  this.eventEmitter = new eventEmitter_1.EventEmitter();
100777
+ // Set options
100778
+ this.disableAutoRecall = options?.disableAutoRecall || false;
100779
+ this.silent = options?.silent || false;
101532
100780
  // Validate Gun instance
101533
100781
  if (!gun) {
101534
100782
  throw new Error("Gun instance is required but was not provided");
@@ -101546,7 +100794,18 @@ class DataBase {
101546
100794
  throw new Error(`Gun instance is invalid: gun.on is not a function. Received gun.on type: ${typeof gun.on}`);
101547
100795
  }
101548
100796
  this.gun = gun;
101549
- this.user = this.gun.user().recall({ sessionStorage: true });
100797
+ // Recall only if NOT disabled and there's a "pair" in sessionStorage
100798
+ if (!this.disableAutoRecall &&
100799
+ typeof sessionStorage !== "undefined" &&
100800
+ sessionStorage.getItem("pair")) {
100801
+ this.user = this.gun.user().recall({ sessionStorage: true });
100802
+ }
100803
+ else {
100804
+ if (!this.silent && !this.disableAutoRecall) {
100805
+ console.log("No pair found in sessionStorage, using gun.user()");
100806
+ }
100807
+ this.user = this.gun.user();
100808
+ }
101550
100809
  this.subscribeToAuthEvents();
101551
100810
  this.crypto = crypto;
101552
100811
  this.sea = sea_1.default;
@@ -101953,7 +101212,13 @@ class DataBase {
101953
101212
  }
101954
101213
  // Attempt to recall user session
101955
101214
  try {
101956
- const recallResult = userInstance.recall({ sessionStorage: true });
101215
+ if (typeof sessionStorage !== "undefined" &&
101216
+ sessionStorage.getItem("pair")) {
101217
+ const recallResult = userInstance.recall({ sessionStorage: true });
101218
+ }
101219
+ else {
101220
+ const recallResult = userInstance;
101221
+ }
101957
101222
  // console.log("recallResult", recallResult);
101958
101223
  }
101959
101224
  catch (recallError) {
@@ -103150,9 +102415,15 @@ class DataBase {
103150
102415
  /**
103151
102416
  * Recall user session
103152
102417
  */
103153
- recall() {
102418
+ recall(options) {
103154
102419
  if (this.user) {
103155
- this.user.recall({ sessionStorage: true });
102420
+ if (typeof sessionStorage !== "undefined" &&
102421
+ sessionStorage.getItem("pair")) {
102422
+ this.user.recall({ sessionStorage: true });
102423
+ }
102424
+ else {
102425
+ this.user;
102426
+ }
103156
102427
  }
103157
102428
  }
103158
102429
  /**
@@ -103200,7 +102471,13 @@ class DataBase {
103200
102471
  */
103201
102472
  saveSession(session) {
103202
102473
  if (this.user) {
103203
- this.user.recall({ sessionStorage: true });
102474
+ if (typeof sessionStorage !== "undefined" &&
102475
+ sessionStorage.getItem("pair")) {
102476
+ this.user.recall({ sessionStorage: true });
102477
+ }
102478
+ else {
102479
+ this.user;
102480
+ }
103204
102481
  }
103205
102482
  }
103206
102483
  /**
@@ -103208,7 +102485,13 @@ class DataBase {
103208
102485
  */
103209
102486
  loadSession() {
103210
102487
  if (this.user) {
103211
- return this.user.recall({ sessionStorage: true });
102488
+ if (typeof sessionStorage !== "undefined" &&
102489
+ sessionStorage.getItem("pair")) {
102490
+ return this.user.recall({ sessionStorage: true });
102491
+ }
102492
+ else {
102493
+ return this.user;
102494
+ }
103212
102495
  }
103213
102496
  return null;
103214
102497
  }
@@ -103245,11 +102528,15 @@ class DataBase {
103245
102528
  exports.DataBase = DataBase;
103246
102529
  // Errors
103247
102530
  DataBase.Errors = GunErrors;
103248
- const createGun = (config) => {
103249
- console.log("Creating Gun instance with config:", config);
103250
- console.log("Config peers:", config?.peers);
102531
+ const createGun = (config, silent) => {
102532
+ if (!silent) {
102533
+ console.log("Creating Gun instance with config:", config);
102534
+ console.log("Config peers:", config?.peers);
102535
+ }
103251
102536
  const gunInstance = (0, gun_1.default)(config);
103252
- console.log("Created Gun instance:", gunInstance);
102537
+ if (!silent) {
102538
+ console.log("Created Gun instance:", gunInstance);
102539
+ }
103253
102540
  return gunInstance;
103254
102541
  };
103255
102542
  exports.createGun = createGun;
@@ -104121,7 +103408,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
104121
103408
  return (mod && mod.__esModule) ? mod : { "default": mod };
104122
103409
  };
104123
103410
  Object.defineProperty(exports, "__esModule", ({ value: true }));
104124
- exports.autoQuickStart = exports.AutoQuickStart = exports.createSimpleAPI = exports.quickStart = exports.QuickStart = exports.SimpleGunAPI = exports.DataBase = exports.GunErrors = exports.derive = exports.crypto = exports.RxJS = exports.SEA = exports.ShogunCore = exports.Gun = exports.MessengerCLI = exports.SHIP_01 = void 0;
103411
+ exports.autoQuickStart = exports.AutoQuickStart = exports.createSimpleAPI = exports.quickStart = exports.QuickStart = exports.SimpleGunAPI = exports.DataBase = exports.GunErrors = exports.derive = exports.crypto = exports.RxJS = exports.SEA = exports.ShogunCore = exports.Gun = void 0;
104125
103412
  const core_1 = __webpack_require__(/*! ./core */ "./src/core.ts");
104126
103413
  Object.defineProperty(exports, "ShogunCore", ({ enumerable: true, get: function () { return core_1.ShogunCore; } }));
104127
103414
  const db_1 = __webpack_require__(/*! ./gundb/db */ "./src/gundb/db.ts");
@@ -104146,12 +103433,6 @@ __exportStar(__webpack_require__(/*! ./utils/errorHandler */ "./src/utils/errorH
104146
103433
  __exportStar(__webpack_require__(/*! ./plugins */ "./src/plugins/index.ts"), exports);
104147
103434
  __exportStar(__webpack_require__(/*! ./interfaces/shogun */ "./src/interfaces/shogun.ts"), exports);
104148
103435
  __exportStar(__webpack_require__(/*! ./config/simplified-config */ "./src/config/simplified-config.ts"), exports);
104149
- var SHIP_01_1 = __webpack_require__(/*! ../ship/implementation/SHIP_01 */ "./ship/implementation/SHIP_01.ts");
104150
- Object.defineProperty(exports, "SHIP_01", ({ enumerable: true, get: function () { return SHIP_01_1.SHIP_01; } }));
104151
- // Export MessengerCLI only in Node.js environment (not browser)
104152
- // This prevents "readline is not a function" errors in browser builds
104153
- var messenger_cli_1 = __webpack_require__(/*! ../ship/examples/messenger-cli */ "./ship/examples/messenger-cli.ts");
104154
- Object.defineProperty(exports, "MessengerCLI", ({ enumerable: true, get: function () { return messenger_cli_1.MessengerCLI; } }));
104155
103436
 
104156
103437
 
104157
103438
  /***/ }),
@@ -104536,7 +103817,7 @@ class CoreInitializer {
104536
103817
  };
104537
103818
  }
104538
103819
  // Initialize storage
104539
- this.core.storage = new storage_1.ShogunStorage();
103820
+ this.core.storage = new storage_1.ShogunStorage(config.silent);
104540
103821
  // Setup error handler
104541
103822
  errorHandler_1.ErrorHandler.addListener((error) => {
104542
103823
  this.core.emit("error", {
@@ -104564,25 +103845,35 @@ class CoreInitializer {
104564
103845
  * Initialize Gun instance
104565
103846
  */
104566
103847
  async initializeGun(config) {
104567
- console.log("Initialize Gun instance", config);
103848
+ if (!config.silent) {
103849
+ console.log("Initialize Gun instance", config);
103850
+ }
104568
103851
  try {
104569
103852
  if (config.gunInstance && config.gunOptions === undefined) {
104570
- console.log("Using provided Gun instance");
103853
+ if (!config.silent) {
103854
+ console.log("Using provided Gun instance");
103855
+ }
104571
103856
  this.core._gun = config.gunInstance;
104572
103857
  }
104573
103858
  else if (config.gunOptions && config.gunInstance === undefined) {
104574
- console.log("Creating new Gun instance");
104575
- this.core._gun = (0, gundb_1.createGun)(config.gunOptions);
103859
+ if (!config.silent) {
103860
+ console.log("Creating new Gun instance");
103861
+ }
103862
+ this.core._gun = (0, gundb_1.createGun)(config.gunOptions, config.silent);
104576
103863
  }
104577
103864
  else if (config.gunInstance && config.gunOptions) {
104578
103865
  // Both provided, prefer gunInstance
104579
- console.log("Both gunInstance and gunOptions provided, using gunInstance");
103866
+ if (!config.silent) {
103867
+ console.log("Both gunInstance and gunOptions provided, using gunInstance");
103868
+ }
104580
103869
  this.core._gun = config.gunInstance;
104581
103870
  }
104582
103871
  else {
104583
103872
  // Neither provided, create a default Gun instance for testing
104584
- console.log("No Gun instance or options provided, creating default instance");
104585
- this.core._gun = (0, gundb_1.createGun)({ peers: config.gunOptions?.peers || [] });
103873
+ if (!config.silent) {
103874
+ console.log("No Gun instance or options provided, creating default instance");
103875
+ }
103876
+ this.core._gun = (0, gundb_1.createGun)({ peers: config.gunOptions?.peers || [] }, config.silent);
104586
103877
  }
104587
103878
  }
104588
103879
  catch (error) {
@@ -104592,8 +103883,10 @@ class CoreInitializer {
104592
103883
  throw new Error(`Failed to create Gun instance: ${error}`);
104593
103884
  }
104594
103885
  try {
104595
- console.log("Initialize Gun instance", this.core.gun);
104596
- this.core.db = new gundb_1.DataBase(this.core._gun, config.gunOptions?.scope || "");
103886
+ if (!config.silent) {
103887
+ console.log("Initialize Gun instance", this.core.gun);
103888
+ }
103889
+ this.core.db = new gundb_1.DataBase(this.core._gun, config.gunOptions?.scope || "", { disableAutoRecall: config.disableAutoRecall, silent: config.silent });
104597
103890
  // Note: user is a getter that returns _user, so we don't need to assign it
104598
103891
  }
104599
103892
  catch (error) {
@@ -104608,7 +103901,15 @@ class CoreInitializer {
104608
103901
  */
104609
103902
  async initializeGunUser() {
104610
103903
  try {
104611
- this.core._user = this.core.gun.user().recall({ sessionStorage: true });
103904
+ // Skip recall if disabled in config
103905
+ if (!this.core.config.disableAutoRecall &&
103906
+ typeof sessionStorage !== "undefined" &&
103907
+ sessionStorage.getItem("pair")) {
103908
+ this.core._user = this.core.gun.user().recall({ sessionStorage: true });
103909
+ }
103910
+ else {
103911
+ this.core._user = this.core.gun.user();
103912
+ }
104612
103913
  }
104613
103914
  catch (error) {
104614
103915
  if (typeof console !== "undefined" && console.error) {
@@ -104617,7 +103918,15 @@ class CoreInitializer {
104617
103918
  throw new Error(`Failed to initialize Gun user: ${error}`);
104618
103919
  }
104619
103920
  this.core.gun.on("auth", (user) => {
104620
- this.core._user = this.core.gun.user().recall({ sessionStorage: true });
103921
+ // Skip recall if disabled in config
103922
+ if (!this.core.config.disableAutoRecall &&
103923
+ typeof sessionStorage !== "undefined" &&
103924
+ sessionStorage.getItem("pair")) {
103925
+ this.core._user = this.core.gun.user().recall({ sessionStorage: true });
103926
+ }
103927
+ else {
103928
+ this.core._user = this.core.gun.user();
103929
+ }
104621
103930
  this.core.emit("auth:login", {
104622
103931
  userPub: user.pub,
104623
103932
  method: "password",
@@ -104651,7 +103960,7 @@ class CoreInitializer {
104651
103960
  */
104652
103961
  setupWalletDerivation() {
104653
103962
  this.core.gun.on("auth", async (user) => {
104654
- if (!user)
103963
+ if (!user.is)
104655
103964
  return;
104656
103965
  const priv = user._?.sea?.epriv;
104657
103966
  const pub = user._?.sea?.epub;
@@ -110259,28 +109568,37 @@ class ShogunStorage {
110259
109568
  /**
110260
109569
  * Initializes storage and loads any existing keypair from localStorage if available
110261
109570
  */
110262
- constructor() {
109571
+ constructor(silent = false) {
110263
109572
  this.store = new Map();
109573
+ this.silent = silent;
110264
109574
  this.isTestMode = "development" === "test";
110265
109575
  this.useLocalStorage = false;
110266
- // Debug: log the environment
110267
- console.log("ShogunStorage: NODE_ENV =", "development");
110268
- console.log("ShogunStorage: isTestMode =", this.isTestMode);
109576
+ // Debug: log the environment (only if not silent)
109577
+ if (!this.silent) {
109578
+ console.log("ShogunStorage: NODE_ENV =", "development");
109579
+ console.log("ShogunStorage: isTestMode =", this.isTestMode);
109580
+ }
110269
109581
  // In test mode, don't use localStorage to avoid test pollution
110270
109582
  if (this.isTestMode) {
110271
109583
  this.useLocalStorage = false;
110272
- console.log("ShogunStorage: Test mode detected, localStorage disabled");
109584
+ if (!this.silent) {
109585
+ console.log("ShogunStorage: Test mode detected, localStorage disabled");
109586
+ }
110273
109587
  return;
110274
109588
  }
110275
109589
  if (typeof localStorage !== "undefined") {
110276
- console.log("ShogunStorage: localStorage is defined");
109590
+ if (!this.silent) {
109591
+ console.log("ShogunStorage: localStorage is defined");
109592
+ }
110277
109593
  try {
110278
109594
  // Probe localStorage without polluting expectations in tests
110279
109595
  const testKey = "_shogun_test";
110280
109596
  localStorage.setItem(testKey, testKey);
110281
109597
  localStorage.removeItem(testKey);
110282
109598
  this.useLocalStorage = true;
110283
- console.log("ShogunStorage: localStorage enabled");
109599
+ if (!this.silent) {
109600
+ console.log("ShogunStorage: localStorage enabled");
109601
+ }
110284
109602
  const storedPair = localStorage.getItem("shogun_keypair");
110285
109603
  if (storedPair) {
110286
109604
  this.store.set("keypair", JSON.parse(storedPair));
@@ -110289,11 +109607,15 @@ class ShogunStorage {
110289
109607
  catch (error) {
110290
109608
  this.useLocalStorage = false;
110291
109609
  // Silence logs in tests; tests expect no console.error during constructor
110292
- console.log("ShogunStorage: localStorage error:", error.message);
109610
+ if (!this.silent) {
109611
+ console.log("ShogunStorage: localStorage error:", error.message);
109612
+ }
110293
109613
  }
110294
109614
  }
110295
109615
  else {
110296
- console.log("ShogunStorage: localStorage is undefined");
109616
+ if (!this.silent) {
109617
+ console.log("ShogunStorage: localStorage is undefined");
109618
+ }
110297
109619
  }
110298
109620
  }
110299
109621
  /**
@@ -110946,43 +110268,7 @@ function generateDeterministicPassword(salt) {
110946
110268
  /******/ return module.exports;
110947
110269
  /******/ }
110948
110270
  /******/
110949
- /******/ // expose the modules object (__webpack_modules__)
110950
- /******/ __webpack_require__.m = __webpack_modules__;
110951
- /******/
110952
- /******/ // expose the module cache
110953
- /******/ __webpack_require__.c = __webpack_module_cache__;
110954
- /******/
110955
110271
  /************************************************************************/
110956
- /******/ /* webpack/runtime/create fake namespace object */
110957
- /******/ (() => {
110958
- /******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
110959
- /******/ var leafPrototypes;
110960
- /******/ // create a fake namespace object
110961
- /******/ // mode & 1: value is a module id, require it
110962
- /******/ // mode & 2: merge all properties of value into the ns
110963
- /******/ // mode & 4: return value when already ns object
110964
- /******/ // mode & 16: return value when it's Promise-like
110965
- /******/ // mode & 8|1: behave like require
110966
- /******/ __webpack_require__.t = function(value, mode) {
110967
- /******/ if(mode & 1) value = this(value);
110968
- /******/ if(mode & 8) return value;
110969
- /******/ if(typeof value === 'object' && value) {
110970
- /******/ if((mode & 4) && value.__esModule) return value;
110971
- /******/ if((mode & 16) && typeof value.then === 'function') return value;
110972
- /******/ }
110973
- /******/ var ns = Object.create(null);
110974
- /******/ __webpack_require__.r(ns);
110975
- /******/ var def = {};
110976
- /******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
110977
- /******/ for(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {
110978
- /******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
110979
- /******/ }
110980
- /******/ def['default'] = () => (value);
110981
- /******/ __webpack_require__.d(ns, def);
110982
- /******/ return ns;
110983
- /******/ };
110984
- /******/ })();
110985
- /******/
110986
110272
  /******/ /* webpack/runtime/define property getters */
110987
110273
  /******/ (() => {
110988
110274
  /******/ // define getter functions for harmony exports
@@ -110995,28 +110281,6 @@ function generateDeterministicPassword(salt) {
110995
110281
  /******/ };
110996
110282
  /******/ })();
110997
110283
  /******/
110998
- /******/ /* webpack/runtime/ensure chunk */
110999
- /******/ (() => {
111000
- /******/ __webpack_require__.f = {};
111001
- /******/ // This file contains only the entry chunk.
111002
- /******/ // The chunk loading function for additional chunks
111003
- /******/ __webpack_require__.e = (chunkId) => {
111004
- /******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
111005
- /******/ __webpack_require__.f[key](chunkId, promises);
111006
- /******/ return promises;
111007
- /******/ }, []));
111008
- /******/ };
111009
- /******/ })();
111010
- /******/
111011
- /******/ /* webpack/runtime/get javascript chunk filename */
111012
- /******/ (() => {
111013
- /******/ // This function allow to reference async chunks
111014
- /******/ __webpack_require__.u = (chunkId) => {
111015
- /******/ // return url for filenames based on template
111016
- /******/ return "" + chunkId + ".shogun-core.js";
111017
- /******/ };
111018
- /******/ })();
111019
- /******/
111020
110284
  /******/ /* webpack/runtime/global */
111021
110285
  /******/ (() => {
111022
110286
  /******/ __webpack_require__.g = (function() {
@@ -111034,52 +110298,6 @@ function generateDeterministicPassword(salt) {
111034
110298
  /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
111035
110299
  /******/ })();
111036
110300
  /******/
111037
- /******/ /* webpack/runtime/load script */
111038
- /******/ (() => {
111039
- /******/ var inProgress = {};
111040
- /******/ var dataWebpackPrefix = "ShogunCore:";
111041
- /******/ // loadScript function to load a script via script tag
111042
- /******/ __webpack_require__.l = (url, done, key, chunkId) => {
111043
- /******/ if(inProgress[url]) { inProgress[url].push(done); return; }
111044
- /******/ var script, needAttach;
111045
- /******/ if(key !== undefined) {
111046
- /******/ var scripts = document.getElementsByTagName("script");
111047
- /******/ for(var i = 0; i < scripts.length; i++) {
111048
- /******/ var s = scripts[i];
111049
- /******/ if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
111050
- /******/ }
111051
- /******/ }
111052
- /******/ if(!script) {
111053
- /******/ needAttach = true;
111054
- /******/ script = document.createElement('script');
111055
- /******/
111056
- /******/ script.charset = 'utf-8';
111057
- /******/ script.timeout = 120;
111058
- /******/ if (__webpack_require__.nc) {
111059
- /******/ script.setAttribute("nonce", __webpack_require__.nc);
111060
- /******/ }
111061
- /******/ script.setAttribute("data-webpack", dataWebpackPrefix + key);
111062
- /******/
111063
- /******/ script.src = url;
111064
- /******/ }
111065
- /******/ inProgress[url] = [done];
111066
- /******/ var onScriptComplete = (prev, event) => {
111067
- /******/ // avoid mem leaks in IE.
111068
- /******/ script.onerror = script.onload = null;
111069
- /******/ clearTimeout(timeout);
111070
- /******/ var doneFns = inProgress[url];
111071
- /******/ delete inProgress[url];
111072
- /******/ script.parentNode && script.parentNode.removeChild(script);
111073
- /******/ doneFns && doneFns.forEach((fn) => (fn(event)));
111074
- /******/ if(prev) return prev(event);
111075
- /******/ }
111076
- /******/ var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
111077
- /******/ script.onerror = onScriptComplete.bind(null, script.onerror);
111078
- /******/ script.onload = onScriptComplete.bind(null, script.onload);
111079
- /******/ needAttach && document.head.appendChild(script);
111080
- /******/ };
111081
- /******/ })();
111082
- /******/
111083
110301
  /******/ /* webpack/runtime/make namespace object */
111084
110302
  /******/ (() => {
111085
110303
  /******/ // define __esModule on exports
@@ -111100,125 +110318,12 @@ function generateDeterministicPassword(salt) {
111100
110318
  /******/ };
111101
110319
  /******/ })();
111102
110320
  /******/
111103
- /******/ /* webpack/runtime/publicPath */
111104
- /******/ (() => {
111105
- /******/ var scriptUrl;
111106
- /******/ if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
111107
- /******/ var document = __webpack_require__.g.document;
111108
- /******/ if (!scriptUrl && document) {
111109
- /******/ if (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')
111110
- /******/ scriptUrl = document.currentScript.src;
111111
- /******/ if (!scriptUrl) {
111112
- /******/ var scripts = document.getElementsByTagName("script");
111113
- /******/ if(scripts.length) {
111114
- /******/ var i = scripts.length - 1;
111115
- /******/ while (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;
111116
- /******/ }
111117
- /******/ }
111118
- /******/ }
111119
- /******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
111120
- /******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
111121
- /******/ if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
111122
- /******/ scriptUrl = scriptUrl.replace(/^blob:/, "").replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
111123
- /******/ __webpack_require__.p = scriptUrl;
111124
- /******/ })();
111125
- /******/
111126
- /******/ /* webpack/runtime/jsonp chunk loading */
111127
- /******/ (() => {
111128
- /******/ // no baseURI
111129
- /******/
111130
- /******/ // object to store loaded and loading chunks
111131
- /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
111132
- /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
111133
- /******/ var installedChunks = {
111134
- /******/ "main": 0
111135
- /******/ };
111136
- /******/
111137
- /******/ __webpack_require__.f.j = (chunkId, promises) => {
111138
- /******/ // JSONP chunk loading for javascript
111139
- /******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
111140
- /******/ if(installedChunkData !== 0) { // 0 means "already installed".
111141
- /******/
111142
- /******/ // a Promise means "currently loading".
111143
- /******/ if(installedChunkData) {
111144
- /******/ promises.push(installedChunkData[2]);
111145
- /******/ } else {
111146
- /******/ if(true) { // all chunks have JS
111147
- /******/ // setup Promise in chunk cache
111148
- /******/ var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
111149
- /******/ promises.push(installedChunkData[2] = promise);
111150
- /******/
111151
- /******/ // start chunk loading
111152
- /******/ var url = __webpack_require__.p + __webpack_require__.u(chunkId);
111153
- /******/ // create error before stack unwound to get useful stacktrace later
111154
- /******/ var error = new Error();
111155
- /******/ var loadingEnded = (event) => {
111156
- /******/ if(__webpack_require__.o(installedChunks, chunkId)) {
111157
- /******/ installedChunkData = installedChunks[chunkId];
111158
- /******/ if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
111159
- /******/ if(installedChunkData) {
111160
- /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type);
111161
- /******/ var realSrc = event && event.target && event.target.src;
111162
- /******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
111163
- /******/ error.name = 'ChunkLoadError';
111164
- /******/ error.type = errorType;
111165
- /******/ error.request = realSrc;
111166
- /******/ installedChunkData[1](error);
111167
- /******/ }
111168
- /******/ }
111169
- /******/ };
111170
- /******/ __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
111171
- /******/ }
111172
- /******/ }
111173
- /******/ }
111174
- /******/ };
111175
- /******/
111176
- /******/ // no prefetching
111177
- /******/
111178
- /******/ // no preloaded
111179
- /******/
111180
- /******/ // no HMR
111181
- /******/
111182
- /******/ // no HMR manifest
111183
- /******/
111184
- /******/ // no on chunks loaded
111185
- /******/
111186
- /******/ // install a JSONP callback for chunk loading
111187
- /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
111188
- /******/ var [chunkIds, moreModules, runtime] = data;
111189
- /******/ // add "moreModules" to the modules object,
111190
- /******/ // then flag all "chunkIds" as loaded and fire callback
111191
- /******/ var moduleId, chunkId, i = 0;
111192
- /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
111193
- /******/ for(moduleId in moreModules) {
111194
- /******/ if(__webpack_require__.o(moreModules, moduleId)) {
111195
- /******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
111196
- /******/ }
111197
- /******/ }
111198
- /******/ if(runtime) var result = runtime(__webpack_require__);
111199
- /******/ }
111200
- /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
111201
- /******/ for(;i < chunkIds.length; i++) {
111202
- /******/ chunkId = chunkIds[i];
111203
- /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
111204
- /******/ installedChunks[chunkId][0]();
111205
- /******/ }
111206
- /******/ installedChunks[chunkId] = 0;
111207
- /******/ }
111208
- /******/
111209
- /******/ }
111210
- /******/
111211
- /******/ var chunkLoadingGlobal = this["webpackChunkShogunCore"] = this["webpackChunkShogunCore"] || [];
111212
- /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
111213
- /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
111214
- /******/ })();
111215
- /******/
111216
110321
  /************************************************************************/
111217
110322
  /******/
111218
- /******/ // module cache are used so entry inlining is disabled
111219
110323
  /******/ // startup
111220
110324
  /******/ // Load entry module and return exports
111221
- /******/ var __webpack_exports__ = __webpack_require__(__webpack_require__.s = "./src/index.ts");
110325
+ /******/ // This entry module is referenced by other modules so it can't be inlined
110326
+ /******/ var __webpack_exports__ = __webpack_require__("./src/index.ts");
111222
110327
  /******/
111223
110328
  /******/ return __webpack_exports__;
111224
110329
  /******/ })()